求助大佬一个fgets()的问题
#include<stdlib.h>#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("C:\\Users\\yyp\\Desktop\\t2.txt","at+");
if(fp == NULL)
{
printf("ERROR\n");
exit(0);
}
else
{
printf("Reading text in txt2:\n");
while((fgets(ch,10,fp)) != NULL)//fgets()作用为:从fp中读取字符并且存储到字符数组ch之中去
{
printf("%s",ch);
}
printf("\n");
}
fclose(fp);
return 0;
}
大佬们,帮忙看看
代码如上,fgets(str,n,fp); 这个函数里面的n意思不是从文件中读取n个字符吗,我取得n是10,那应该是读取9个字符到ch中并且输出呀。
我文档里的内容是这样的 adf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbb 本帖最后由 jackz007 于 2021-3-9 10:58 编辑
#include<stdio.h>
int main(void)
{
FILE * fp ;
char ch ;
if((fp = fopen("C:\\Users\\yyp\\Desktop\\t2.txt","r")) != NULL) {
fgets(ch , 10 , fp) ;
while(! feof(fp)) {
printf("%s\n" , ch);
fgets(ch , 10 , fp);
}
fclose(fp) ;
} else {
fprintf(stderr , "ERROR\n");
}
}
通过这个代码,你会发现,确实是每次读取了 9 个字符。
编译、运行实况
D:\0002.Exercise\C>g++ -o x x.c
D:\0002.Exercise\C>x
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
adf212342
131aaabbb
D:\0002.Exercise\C>
如果希望照原样打印文件内容
#include<stdio.h>
int main(void)
{
FILE * fp ;
char ch ;
if((fp = fopen("C:\\Users\\yyp\\Desktop\\t2.txt","r")) != NULL) {
fgets(ch , 10 , fp) ;
while(! feof(fp)) {
printf("%s" , ch) ;
fgets(ch , 10 , fp);
}
fclose(fp) ;
printf("\n") ;
} else {
fprintf(stderr , "ERROR\n");
}
}
编译、运行实况
D:\0002.Exercise\C>g++ -o x x.c
D:\0002.Exercise\C>x
adf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf21234
2131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaabbbadf212342131aaab
bb
D:\0002.Exercise\C>x >
页:
[1]