How to read and overwrite text file in C?
Asked Answered
R

5

7

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
Robb answered 2/7, 2015 at 14:58 Comment(4)
You can't overwrite the file while you're reading it. Well, you can, but you get garbled data. What's your OS? If it's Linux/Unix, just delete the file after you open it - unlink( "text.txt" ); - then open a new file with the same name and write the modified lines into the new file. You'll have two FILE * variables.Lyudmila
It must be positioned at the beginning of the line.Expiration
Rewriting files in-place is tricky. One little-known important fact is that when you've read to the exact spot where you want to start writing, you have to call something like fseek(fp, 0, SEEK_CUR) before you start writing. And then again after you're done writing, before you start reading again.Flashlight
always check (!=NULL) the returned value from malloc() to assure the operation was successful. always check (!=NULL) the returned value from fopen() to assure the operation was successful.Intransitive
E
6
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
}
Expiration answered 2/7, 2015 at 15:13 Comment(4)
@NattachaiSuteerapongpan See 7.21.5.3 The fopen function p7 of n1570.pdfExpiration
I know you your comment was replied 2 years ago but I've just read your answer and I'm not really clear about "fflush()". Your code work absolutely fine but then I have tried remove "fflush(fp)" and run the code. The program stuck in infinite loop. Since I broke the program, it produce very weird result. I have really no idea why result look like. Could you please help me explain why removing fflush produce a result like this. Here is the link of text file(before and after execute program). drive.google.com/drive/folders/…Arni
@NattachaiSuteerapongpan It is necessary to call fflush as written in the link shown in the previous comment. It does not always work correctly if it does not exist. Briefly explained, it is buffered, so it needs to be reflected in the actual file.Expiration
@ BLUEPIXY Thanks a lot for your reply:) I've got a lot of ideas from your link mentioned above.Arni
K
3

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
Karmakarmadharaya answered 2/7, 2015 at 17:47 Comment(0)
H
0

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

Helminth answered 27/4, 2016 at 12:51 Comment(0)
B
0
// 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;
}
Beachhead answered 15/5, 2017 at 7:25 Comment(1)
Although it may seem obvious, what certain code fragments are used to, please consider using code comments or documentation references, when answering a question, so people get additional background information.Cither
M
0
// 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;
}
Mathias answered 17/5, 2017 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.