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
I always suggest to use another file do this kindda solutions.
try this out
I worked this out on windows