|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码如下。其中fopen打开的文件中只有一串数字1234567890。
- 1 #include <stdio.h>
- 2 #include <stdlib.h>
- 3
- 4 int main(void)
- 5 {
- 6 char ch;
- 7 FILE * fp;
- 8
- 9 fp = fopen("num", "rb");
- 10 fseek(fp, -1L, SEEK_END);
- 11 ch = getc(fp);
- 12 fclose(fp);
- 13 if ('\n' == ch)
- 14 puts("aaa");
- 15 else
- 16 putchar(ch);
- 17
复制代码 运行结果为:
- [root@localhost test13]# ./a.out
- aaa
- [root@localhost test13]#
复制代码 这个换行符哪来的呢?
首先,确认一下 "num" 文件是否以换行符结束。有时编辑器会在文件结尾自动添加换行符。
你可以尝试以下方法来查看 "num" 文件的内容:
这个命令会显示文件中的所有字符,包括换行符。如果文件的结尾是一个换行符(通常显示为 $ 符号),那么你的代码的输出就是正确的。
另外,在使用 fseek() 函数时,建议检查其返回值是否为 0,以确保定位操作成功。
以下是你的代码的一个修改版本,加入了错误检查:
- #include <stdio.h>
- #include <stdlib.h>
- int main(void)
- {
- char ch;
- FILE *fp;
- fp = fopen("num", "rb");
- if (!fp)
- {
- perror("Error opening file");
- exit(EXIT_FAILURE);
- }
- if (fseek(fp, -1L, SEEK_END) != 0)
- {
- perror("Error seeking in file");
- fclose(fp);
- exit(EXIT_FAILURE);
- }
- ch = getc(fp);
- fclose(fp);
- if ('\n' == ch)
- puts("aaa");
- else
- putchar(ch);
- return 0;
- }
复制代码
这个修改后的代码会检查 fopen() 和 fseek() 的返回值,并在遇到错误时输出错误信息。如果问题仍然存在,可以进一步检查文件的内容和格式。
|
|