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
mpromonet
  • 11,326
  • 43
  • 62
  • 91
Corey
  • 115
  • 1
  • 1
  • 6
  • 2
    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. – Andrew Henle Jul 02 '15 at 15:02
  • It must be positioned at the beginning of the line. – BLUEPIXY Jul 02 '15 at 15:05
  • 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. – Steve Summit Jul 02 '15 at 15:09
  • 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. – user3629249 Jul 03 '15 at 03:30

5 Answers5

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
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 1
    @NattachaiSuteerapongpan See **7.21.5.3 The fopen function p7** of [n1570.pdf](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) – BLUEPIXY Sep 19 '17 at 08:12
  • 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). https://drive.google.com/drive/folders/0B3cRfiRmMzw6Q01fZ09uX0VOU2c?usp=sharing – Xiao Sep 19 '17 at 08:23
  • 1
    @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. – BLUEPIXY Sep 19 '17 at 08:30
  • @ BLUEPIXY Thanks a lot for your reply:) I've got a lot of ideas from your link mentioned above. – Xiao Sep 19 '17 at 08:30
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
Mayukh Sarkar
  • 2,289
  • 1
  • 14
  • 38
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

ChandraKumar
  • 515
  • 4
  • 14
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;
}
  • 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. – Lepidopteron May 15 '17 at 07:41
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;
}