【发布时间】:2015-12-11 15:46:16
【问题描述】:
我目前正在尝试做自己的 shell,它必须是多语言的。 所以我尝试实现一个函数来读取 .txt 文件中的行。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = *line;
i++;
}
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
}
我在 win7 上,但我在 VM 上使用 gcc 编译。
我有一个警告说:
format'%s' expects argument of type 'char *', but argument 2 (and 3) has type 'int' [-Wformat=]
我尝试使用 %d 而不是 %s 执行 prog,它会打印数字。
我不明白是什么将我的 aMsg 转换为 int。
我的 try.txt 文件只是:
Hi
Quit
【问题讨论】:
-
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT])-->printf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT])BTW 我不知道这条指令是否符合你的要求。 -
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);看起来不对。也许你想要printf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT]);?不要free(line);,因为你还没有malloced。 -
@Cool Guy 现在它会打印我的 HQ 和 Q...但没有编译错误 ;)
-
我认为您误解了您的代码的作用。该 printf 打印从
index 0的aMsg数组开始的NULL terminated string和从aMsg数组的index 1开始的NULL terminated string。可能您希望char *aMsg[512];根据指针数组更改您的代码。 -
这篇文章没有提出任何问题。选择的答案提供了工作代码,没有解释。其他答案解释并提供了代码的工作 sn-ps。似乎需要“鱼”而不是 fishing lesson"。
标签: c gcc gcc-warning