Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and overwrite text file in C?

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
like image 523
Corey Avatar asked Jul 02 '15 14:07

Corey


1 Answers

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
}
like image 81
BLUEPIXY Avatar answered Sep 20 '22 14:09

BLUEPIXY