How to read and overwrite text file in C?

2019-04-26 17:48发布

I have a text file text.txt that reads (for simplicity purposes)

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

Again for simplicity's sake, I am just trying to set the first character in each line to 'x', so my desired result would be

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

So I am opening the text.txt file and trying to overwrite each line with the desired output to the same text file. In the while loop, I set the first character in each line to 'x'. I also set the variable "line" equal to one, because if its on the first line, I want to rewind to the beginning of the file in order to overwrite at the start instead of at the end of the file. Line is then incremented so it will skip the rewind for the next iteration, and should continue to overwrite the 2nd and 3rd lines. It works perfectly for the first line.

Anybody have any solutions? BTW, I have researched this extensively both on stackoverflow and other sites, and no luck. Here's my code and my output is also below:

#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);
}

Output:

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

5条回答
Explosion°爆炸
2楼-- · 2019-04-26 18:08
// 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;
}
查看更多
Animai°情兽
3楼-- · 2019-04-26 18:17
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
}
查看更多
Lonely孤独者°
4楼-- · 2019-04-26 18:20

I always suggest to use another file do this kindda solutions.

  1. Read the line
  2. Put x in a new file in a line and the copy the rest of the line.
  3. Do this till you get EOF
  4. remove the old file
  5. rename this new file
查看更多
看我几分像从前
5楼-- · 2019-04-26 18:24
// 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;
}
查看更多
Melony?
6楼-- · 2019-04-26 18:32

try this out

#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;
    }

I worked this out on windows

查看更多
登录 后发表回答