简体   繁体   English

我可以写入一个新文件,然后在同一C程序中读取该文件吗?

[英]Can I write to a new file, then read from that file within the same C program?

FILE *new = fopen("new.out", "w+"); // creates a new file that didnt exist before
char finput[50];

fprintf(new, "hello\nworld\n");

while(fgets(finput, 51, new) != NULL)
{ /*never reaches this point*/ }

What am I doing wrong? 我究竟做错了什么? If I write to a file that doesn't already exist, is it possible to read from that file later on? 如果我写入的文件尚不存在,以后是否可以读取该文件?

You should rewind or fseek before reading again. 你应该rewindfseek再次读数。 And please, don't call a variable new (because that is a C++ keyword). 并且,请不要将变量称为new (因为这是C ++关键字)。

You need to do something to change the mode between write and read. 您需要执行一些操作以更改写入和读取之间的模式。 fseek is a possibility. fseek是可能的。

On streams open for update (read+write), a call to fseek allows to switch between reading and writing. 在打开以进行更新(读+写)的流上,对fseek的调用允许在读和写之间切换。

fsetpos and rewind work as well. fsetposrewind工作也是如此。

You've opened the file in w+ mode, which is read/write in append mode. 您已在w+模式下打开文件,该模式在附加模式下可读写。 After your fprintf() command, the file pointer is at the END of the file, meaning there's nothing to read but EOF. 在执行fprintf()命令后,文件指针位于文件的末尾,这意味着除EOF外没有其他要读取的内容。 You have to fseek() to another point in the file, or rewind() to the beginning. 您必须fseek()到文件中的另一点,或rewind()到开头。

Take a look here . 在这里看看。 They advice you to check errno on error. 他们建议您检查errno You can use 您可以使用

perror("Fgets failed");

to print full error message. 打印完整的错误消息。

To the problem: you need to call fseek when changing from write to read (always). 问题:从写入更改为读取(始终)时需要调用fseek

fseek(new, 0, SEEK_SET);

rewinds the file. 倒带文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM