我正在尝试一次读取一个文件的一行,打印出该行,然后分析每个字符以确定如何处理它(所有分析都在驱动程序中进行,如果字符是除字母或数字之外的任何内容)
我当前的输入文件是:
Hello$ is
asd
这就是我一次读一行的方法:
char GetSourceChar() {
char line[MAXLINE];
if (changeLine == 1) {
if (fgets(line, sizeof line, file) != NULL) {
char str1[10];
sprintf(str1,"%d", row); // convert int to 'string'
printf("[");
printf(str1);
printf("] ");
fprintf(outFile, "%s", "[");
fprintf(outFile, "%s", str1);
fprintf(outFile, "%s", "] ");
printf("%s", line);
fprintf(outFile, "%s", line);
changeLine = 0;
}
}
char c = line[col];
if (c == '\r'){
changeLine = 1;
row++;
col = 0;
}
col++;
return c;
}
然后这是我的输出:
[0] hello$ hi
^
Incorrect Character
[1] asd
这正是我想要的样子,但如果我将我的输入文件更改为哪怕再长一个字,它也不起作用吗?我注意到错误发生在我说的地方
char c = line[col]
它没有返回正确的字符,只返回\000,所以在那之后似乎没有什么能正常工作。
有什么想法吗?
最佳答案
line
数组在本地声明为 GetSourceChar()
,因此在调用之间超出了范围。因此它的内容在函数返回后可能(也可能不会)被覆盖,并且在您下次调用该函数时它可能(或可能不)包含意外值。
您可以通过以下方式解决此问题:
- 在函数中将其声明为
static
,或者 - 在调用函数中声明它并将其作为参数传递,或者
- 在全局范围内声明它。
此外,您可以替换所有这些
char str1[10];
sprintf(str1,"%d", row); // convert int to 'string'
printf("[");
printf(str1);
printf("] ");
fprintf(outFile, "%s", "[");
fprintf(outFile, "%s", str1);
fprintf(outFile, "%s", "] ");
printf("%s", line);
fprintf(outFile, "%s", line);
与
printf("[%d] %s", row, line);
fprintf(outFile, "[%d] %s", row, line);
关于c - 逐行读取文件,分析字符 --- C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509866/