在 file.txt 中我有以下内容:
We are
in 2012
我想打印第二个字符,即“e”,但下面的程序显示空白。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
FILE *file;
file = fopen("file.txt", "r");
c = getc(file+1);
putchar(c);
fclose(file);
return 0;
}
如何正确打印第二个字符? (当我只是在 getc 中传递文件时,它会打印 w。)
最佳答案
文件不是指向内存缓冲区的指针。
FILE* file;
它是指向文件结构的指针。通过向 getc() 提供 (file+1) 参数,您只是为其提供了一个未初始化的区域作为输入。
答案很简单:要么调用 getc() 两次; 或者,因为这可能是一个练习,您可以使用 fseek() 将文件指针移动到正确的位置。它变成了:
fseek(file, 1, SEEK_SET);
c = getc(file);
putchar(c);
关于c - 递增文件指针后打印文件中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19297211/