如何在 c 中使用 fopen "w+" 来写入和读取同一个文件?

  • 本文关键字:读取 同一个 文件 fopen c
  • 更新时间 :
  • 英文 :


我正在寻找如何使用C编写和读取文件。在发现usign fopen("foo","r+")或fopen("foo","w+")应该是可能的之后,我决定创建一个虚拟程序来尝试它。这是程序:

#include <stdio.h>
int main(){
    char reader[81];
    FILE *USE = fopen("dummy.txt", "w+");
    fprintf(USE,"whatever rnhello");
    while(fgets(reader, 80, USE)) {
        printf("%s", reader);
    }
    fclose(USE);
    return 0;
}

这个想法是创建一个名为 dommy.txt 的新文件。每次执行此程序时,都会在虚拟文件中写入 2 行.txt然后在命令行或终端中显示这些行。如您所见,它不是有史以来最有用的程序,但是知道如何执行此操作在未来会非常有帮助。

任何帮助都是好的

要再次读取文件,您应该使用rewind函数:

 fprintf(USE,"whatever rnhello");
 rewind(USE); // put the file pointer to the begin of file;
 while(fgets(reader, 80, USE));

另一种方法是使用fseek

int fseek(FILE *stream, long int offset, int whence)

哪里:

  • stream − 这是指向标识流。

  • 偏移量 − 这是要从何时偏移的字节数。

  • 从哪里 − 这是添加偏移的位置。是的
    由以下常量之一指定:

    1 - SEEK_SET    Beginning of file
    2 - SEEK_CUR    Current position of the file pointer
    3 - SEEK_END    End of file
    

您也可以使用:

long int ftell ( FILE * stream ); 

对于流中的当前位置。

在这里,更多关于 fseek vs 倒带

您忘了倒带文件:

fprintf(USE,"whatever rnhello");
rewind(USE);   //<<< add this
while(fgets(reader, 80, USE)) {

写入文件后,文件指针位于文件末尾。因此,为了读取所写的内容,您必须使用 rewind 将文件指针设置为文件的开头。

如果要将文件指针放在开头以外的其他位置,请使用 fseek。ftell会告诉你文件指针当前在哪里。

与您的问题无关的旁注

不要使用所有大写变量名称,例如USE,所有大写名称通常仅用于宏。

我的解决方案,不要使用 w+ 而是使用 r+。

文件顶部

#include <stdio.h>
#include <stdlib.h>

全球

FILE * g_file;

打开文件

int openFile() {
    g_file = fopen("my_file.txt", "r+");
    if( g_file == NULL )
    {
        // No file ?
        g_file = fopen("my_file.txt", "w+");
    }
    return 0;
}

读写

#define MAX 64
#define true  1
#define false 0
int writeReadFile() {
    char line[MAX] = "";
    int size = 0;
    while( fgets(line, MAX, g_file) )
    {
        // Check something
        // result = sscanf(line, etc...)
        // if ( result == argument number ok) ...
        // strcmp( ? , ? ) == 0
        // strlen compare size of the previous line and new line   
        if ( true ) {
            size = ftell(g_file);
        }
        // Replace something
        if( true ) {
            fseek(g_file, size, SEEK_SET);            
            // fputc if size differ
            // fprintf if size ok
        }
        size = ftell(g_file);
    }
    fprintf(g_file, "%sn", "info");
}

主要

int main(void)
{
    printf("Hello World !n");
    openFile();
    writeReadFile();
    return 0;
}

请不要删除我的帖子。一旦我写了这个。我从页面收到链接,保存它,我可以将其重新用于其他代码。因此,请勿删除。谢谢。

他在我这边编译,也希望你。删除并且不要放置不好的笔记。

最新更新