如何在 C 中读取和覆盖文本文件?

Posted

技术标签:

【中文标题】如何在 C 中读取和覆盖文本文件?【英文标题】:How to read and overwrite text file in C? 【发布时间】:2015-09-20 04:31:18 【问题描述】:

我有一个文本文件 text.txt 读取(为简单起见)

this is line one
this is line two
this is line three

再次为简单起见,我只是想将每行中的第一个字符设置为“x”,所以我想要的结果是

xhis is line one
xhis is line two
xhis is line three

所以我打开 text.txt 文件并尝试用所需的输出覆盖每一行到同一个文本文件。在 while 循环中,我将每行中的第一个字符设置为“x”。我还将变量“line”设置为等于一,因为如果它在第一行,我想倒退到文件的开头,以便在文件的开头而不是结尾覆盖。然后行增加,因此它将跳过下一次迭代的倒带,并应继续覆盖第 2 和第 3 行。它非常适合第一行。

有人有解决办法吗?顺便说一句,我在 *** 和其他网站上对此进行了广泛的研究,但没有运气。这是我的代码,我的输出也在下面:

#include <stdio.h>
#include <stdlib.h>
#define MAX 500

int main() 
    char *buffer = malloc(sizeof(char) * MAX);
    FILE *fp = fopen("text.txt", "r+");
    int line = 1;
    while (fgets(buffer, 500, fp) != NULL) 
            buffer[0] = 'x';
            if (line == 1) 
                    rewind(fp);
                    fprintf(fp, "%s", buffer);
            
            else 
                    fprintf(fp, "%s", buffer);
            
            line++;
    
    free(buffer);
    fclose(fp);

输出:

xhis is line one
this is line two
xhis is line two
e
x

【问题讨论】:

您不能在阅读时覆盖文件。好吧,你可以,但你得到的数据是乱码。你的操作系统是什么?如果是 Linux/Unix,只需在打开文件后删除文件 - unlink( "text.txt" ); - 然后打开一个 new 同名文件并将修改后的行写入新文件。您将有 两个 FILE * 变量。 必须位于行首。 就地重写文件很棘手。一个鲜为人知的重要事实是,当您阅读到要开始写作的确切位置时,您必须在开始写作之前致电fseek(fp, 0, SEEK_CUR)@ 之类的东西。然后在你写完之后再开始阅读。 始终检查 (!=NULL) malloc() 的返回值以确保操作成功。始终检查 (!=NULL) fopen() 的返回值以确保操作成功。 【参考方案1】:
long pos = ftell(fp);//Save the current position
while (fgets(buffer, 500, fp) != NULL) 
    buffer[0] = 'x';
    fseek(fp, pos, SEEK_SET);//move to beginning of line
    fprintf(fp, "%s", buffer);
    fflush(fp);
    pos = ftell(fp);//Save the current position

【讨论】:

@NattachaiSuteerapongpan 见n1570.pdf的7.21.5.3 fopen函数p7 我知道你的评论是在 2 年前回复的,但我刚刚阅读了你的答案,我对“fflush()”并不是很清楚。您的代码工作得很好,但后来我尝试删除“fflush(fp)”并运行代码。程序陷入无限循环。由于我破坏了程序,它产生了非常奇怪的结果。我真的不知道为什么结果看起来像。您能否帮我解释一下为什么删除 fflush 会产生这样的结果。这是文本文件的链接(执行程序之前和之后)。 drive.google.com/drive/folders/… @NattachaiSuteerapongpan 有必要拨打fflush,如上一条评论中显示的链接中所述。如果它不存在,它并不总是能正常工作。简单解释一下,是缓冲的,所以需要在实际文件中体现出来。 @BLUEPIXY 非常感谢您的回复:)我从您上面提到的链接中得到了很多想法。【参考方案2】:

我总是建议使用另一个文件来做这种解决方案。

    阅读该行 将 x 放入新文件的一行中,然后复制该行的其余部分。 这样做直到你得到 EOF 删除旧文件 重命名这个新文件

【讨论】:

【参考方案3】:

试试这个

#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()

    char buffer[500],read[50][50];
    FILE *fp=fopen("text.txt","r+");
    int line =1;
    while(fgets(buffer,500,fp)!=NULL)
        buffer[0]='x';
        printf("\n%d ",line);
        puts(buffer);
        strcat(read[line-1],(const char*)buffer);
        line++;
    
    fclose(fp);
    FILE *fp1=fopen("text.txt","w");
    rewind(fp1);
    fprintf(fp1,"%s",read);
    return 0;
    

我在windows上解决了这个问题

【讨论】:

【参考方案4】:
// file_overwrite.cpp : main project file.
// File opens and write y value to a file
// again reads same file and re-writes y value to a file

#include "stdafx.h"

using namespace System;

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

int main(int argc, char *argv[])

    int x = 19530;

    FILE *fp1 = fopen("D:\\Data\\BUFF.txt","w+");

    if(fp1 == NULL)
        printf("File not opening \n");
        int y=x;
        fprintf(fp1, "%d \n", y);
        fclose(fp1);
        printf("\n file -> open -> write y value and close");


        freopen("D:\\Data\\BUFF.txt", "w", fp1);
        rewind(fp1);
        y=100;
        fprintf(fp1, "%d \n", y);
        printf("\n file -> Reopen -> rewind write y values and close");
        fclose(fp1);

       getch();
       return 0;

【讨论】:

虽然看起来很明显,但某些代码片段的用途,请在回答问题时考虑使用代码 cmets 或文档参考,以便人们获得额外的背景信息。【参考方案5】:
// overwrite_file.cpp 
// File opens and write y value to a file
// again reads same file and re-writes y value to a file

#include "stdafx.h"

using namespace System;

#include<stdio.h>
#include<stdio.h>
#include<string.h>                //Include appropriate headers
#include <conio.h>
#include<stdlib.h>

int main(int argc, char *argv[])

    int x = 19530;                            // Give any value in the limit

    FILE *fp1 = fopen("D:\\Data\\BUFF.txt","w+");   // open file to write

    if(fp1 == NULL)                                 // if the file pointer encounters a null, it may not open neither overwrite 
        printf("File not opening \n");
        int y=x;                                     
        fprintf(fp1, "%d \n", y);                   //print y
        fclose(fp1);
        printf("\n file -> open -> write y value and close");  // close the file after writing the value of y


        freopen("D:\\Data\\BUFF.txt", "w", fp1);            //reopen and rewind file 
        rewind(fp1);
        y=100;                                              // this value of y given within the limits gets printed on the .exe console
        fprintf(fp1, "%d \n", y);
        printf("\n file -> Reopen -> rewind write y values and close");    // rewind write values and close 
        fclose(fp1);

       getch();
       return 0;

【讨论】:

以上是关于如何在 C 中读取和覆盖文本文件?的主要内容,如果未能解决你的问题,请参考以下文章

逐行写入文本文件 c

在 C 中,我应该如何读取文本文件并打印所有字符串

在C++中如何读取文本中的数据存储为数组变量?

C++文件读写操作逐字符读取文本和逐行读取文本

如何在c中读取二进制文件? (视频、图像或文本)

vba adodb读取文本文件