C语言fgets怎么检测到文件末尾的?c 中fgets的返回值NULL,结尾不就是换行符吗?

15:02 提问
C语言中的fgets问题,结果输出多出一行“(null)”
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
char* main01()
//写文件操作
char* FileName="c:/1.txt";
char ch[]="\n\r";
FILE* fp=NULL;
fp=fopen(FileName,"wb");
if(fp == NULL)
printf("open file error:\n");
fputc('c',fp); //写一个字符
fputs("abcdefg",fp);//写一个字符串
fwrite(ch,2,1,fp); //写入时换行
fprintf(fp,"\n\r"); //写入时换行
fputs("hijklmn\n",fp);
fclose(fp);
return FileN
void main03(char* file_name)
//fgets读文件操作
char* FileName=file_
char buf[100];
FILE* fp=NULL;
fp=fopen(FileName,"r");
if(fp == NULL)
printf("Open file error:\n");
while( !feof(fp))
printf("%s",fgets(buf,100,fp));
fclose(fp);
system("pause");
void main()
char* File_Name=main01();
main03(File_Name);
system("pause");
运行结果:
(null)请按任意键继续. . .
(null)是指什么意思?我再文件里没有写入“(null)”
按赞数排序
哦,知道了。原来是fputs会自动增加一个换行符,所以,导致文件指针读取该空白行时会多出一个(null)
fputs("hijklm\n",fp);你这句话里面给你写了个换行符,把换行符去掉fputs("hijklm",fp);C语言读取文件一行以及换行符的问题
记下来免得自己忘了。
char *fgets(
The fgets function reads
a string from the input stream argument and stores it
in str. fgets reads characters from the
current stream position to and including the first newline
character, to the end of the stream, or until the number of
characters read is equal to n & 1, whichever comes
first. The result stored in str is appended with a
null character. The newline character, if read, is included in the
fgets从流的当前位置读取字符存到str中,碰到行尾、文件尾或者读到了n-1个字符就停止读取,并在存储的字符串末尾加上null字符作为字符串的结尾(读n-1个字符,加上null字符正好n个)。如果读到了换行符,也会将其存入str中。
对于换行符,msdn介绍fread时说了 :If the given
stream is opened in text mode, carriage return&linefeed pairs are
replaced with single linefeed characters. The replacement has no
effect on the file pointer or the return value.
如果是以文本方式打开的文件流,那么读入到str中的回车换行对(\r\n)会被替换为一个换行字符(\n)。可是,文件流本身中的\r\n并没有被替换成\n,因此这种替换并不会影响文件指针的位置,也不影响返回值。也就是说,在处理指针偏移量的时候,还是要把回车换行的长度记为2,而不是1。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。09-1609-0109-0708-13
04-0904-0801-1710-04
◇本站云标签
◇热点推荐2013年 总版技术专家分年内排行榜第三
2012年 总版技术专家分年内排行榜第七
本帖子已过去太久远了,不再提供回复功能。

我要回帖

更多关于 fgets返回值 的文章

 

随机推荐