本文介绍了阅读C语言编程/写文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要写东西到一个txt文件,并阅读其内容,然后打印在屏幕上。
下面是code自己编写的,它可以创建并正确内容写入文件,但它不能从文件和打印正确读取。
I need to write something into a txt file and read the contents, then print them on the screen.Below is the code I have written, it can create and write contents into file correctly, but it cannot read from the file and print correctly.
#include<stdio.h>
#include<stdlib.h>
main()
{
char filename[20]={"c:\\test.txt"};
FILE *inFile;
char c;
inFile=fopen(filename,"w+");
if(inFile==NULL)
{
printf("An error occoured!");
exit(1);
}
while((c=getchar())!=EOF)
fputc(c,inFile);
fputc('\0',inFile);
while((c=fgetc(inFile))!=EOF)
putchar(c);
}
会有人告诉我有什么不对的程序,特别是最后两行。
提前致谢。
Would someone tell me what's wrong with this program, especially the last two lines.Thanks in advance.
推荐答案
您需要添加
fseek(inFile, 0, SEEK_SET);
在
while ((c=fgetc(inFile)) != EOF)
putchar(c);
,因为文件指针(未所述一个用于存储器分配)已移动到了最后。从文件中读取,你必须将其带到与 fseek的
函数的前面。
这篇关于阅读C语言编程/写文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!