不明白为什么一个fgetc函数读到了换行,另一个读不到,我的想法是fscanf会舍弃末尾换行符,但网上资料说换行符仍在流中
根据参考链接,推测,fscanf()函数里的 换行符\n , 制表符\t, 以及空格的效果都是一样的,即跳过连续空白间隔(空白间隔,包括换行,制表符,空格),所以第一个fscanf()里的制表符\t直接跳过了结尾的制表符和换行,所以fgetc()读取不到换行了。
测试代码如下:
参考链接:
#include <stdio.h>
int main(void){
FILE * fp = fopen("data0515.txt","r");
if(fp==NULL){
printf("文件打开失败!\n");
return -1;
}
int a,b,c,d,e,f;
char ch1,ch2,ch3,ch4;
// https://zhuanlan.zhihu.com/p/151026519
// fscanf()函数里使用空格,制表符,换行符会跳过连续的空白间隔(
// 即 空格,制表符,换行符都会跳过
fscanf(fp,"%d%d%d\t",&a,&b,&c);
ch2=fgetc(fp);
printf("a=%d, b=%d, c=%d, ch2=%c,%d, \n",a,b,c,ch2,ch2);
fscanf(fp,"%d%d%d",&d,&e,&f);
ch3=fgetc(fp);
ch4=fgetc(fp);
printf("d=%d, e=%d, f=%d, ch3=%c,%d, ch4=%c,%d\n",d,e,f,ch3,ch3,ch4,ch4);
return 0;
}
data0515.txt(测试文件):
1 2 3
4
5 6 7
还是用结构体来举例,不过这次是将文件中的数据存入内存中:
#include <stdio.h> struct student{ char name[20]; int age; char sex[10]; }; int main() { struct student xxs = { 0 }; FILE* pf = fopen("test2.txt", "r"); if(pf == NULL) { printf("文件打开失败\n"); return 0; } fscanf(pf, "%s %d %s", xxs.name, &(xxs.age), xxs.sex); printf("%s %d %s", xxs.name, xxs.age, xxs.sex); fclose(pf); pf = NULL; return 0; }
程序运行结果如下:
通过两个例子可以看出,fprintf
和 fscanf
两个函数,可以对内存或者文件中的 格式化的数据 进行读写的操作。并且呢,两个函数的的使用方法与 printf
scanf
两个函数的使用方法 十分的相似。