I have a text.txt text file that reads (for simplicity)
this is line one this is line two this is line three
Again, for simplicity, I'm 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 open the text.txt file and try to rewrite each line with the desired output in the same text file. In a while loop, I set the first character in each line to "x". I also set the string variable to one, because if it's on the first line, I want to rewind to the beginning of the file to overwrite at the beginning, not the end of the file. Then the line grows, so it skips rewinding for the next iteration and should continue to replace the second and third lines. It works great for the first line.
Anyone have any solutions? By the way, I researched this extensively on both stackoverflow and other sites, and no luck. Here my code and my output are 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
Corey source share