我创建了一个程序来模仿 Linux 中的“cat”命令。 我想制作一个程序来满足“cat”的“-n”选项,显示行号以及文件内容。 这是我到目前为止所做的事情。
int numline = 1;
int i = 2;
printf("\t%d ", numline);
for(i; i < argc ; i++)
{
fptr = fopen(argv[i], "r");
if(fptr == NULL)
{
printf("Can not open file");
return -1;
}
c = fgetc(fptr);
while(c != EOF)
{
if(c == '\n')
{
numline++;
printf("\n\t%d ", numline);
}
else
printf("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
}
这是一个示例输出。
1 hi how are you
2
3
4 i am fine
5
6 thank you
7
8 bye
9 cya
10 garbage text
11
12
13 bye
14
问题出在第 14 行。文件在第 13 行结束,但程序仍然打印第 14 行。我该如何纠正这个问题? 谢谢。
最佳答案
读取时,'\n'
表示文本文件中的行尾,而不是新行的开始,即使 C 称其为新行 .
不要通过测试 if (c == '\n')
来确定新行,而是检查前一个 c 是否为 '\n'
。
请务必使用int c
。
// Commented out, not needed
// printf("\t%d ", numline);
int c;
int previous_c = '\n';
while((c = fgetc(fptr)) != EOF) {
if (previous_c == '\n') {
numline++;
printf("%d ", ++numline);
}
printf("%c", c);
previous_c = c;
}
由于输入的最后一个字符可能与 '\n'
不同,代码可以在循环后检测到该字符并添加一个。
if (previous_c != '\n') {
printf("\n");
}
关于c - 我怎样才能纠正这个代码,以便它给出预期的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164304/