The following code will insert a line into the file at line 6, i.e., the original line 6 will be moved back one line at a time.
#include <stdio.h>
int main(void)
{
FILE *fp;
int i;
char buf[1024]; // Assuming that each line is no more than 1024 bytes, adjusting the size as appropriate.
if (! (fp = fopen(". /a.txt", "r+"))) { // Try to open the file as a read/write.
fprintf(stderr, "Open failed.\n");
return 1;
}
for (i = 0; i < 5; i++) { // Loop 5 times, read the first 5 lines
fgets(buf, 1024, fp); // Read one line. read one line
}
// At this point, the file pointer is at the beginning of line 6
long offset = ftell(fp); // Record the position of the file pointer, because there is more to be read later, and the file pointer will be moved
// Here, for the sake of the program's ease of comprehension, we're assuming that the next line will be no more than 100 lines long, and that each line will be no more than 1024 bytes, otherwise we'll need to use a chained list or a binary list. Otherwise, you need to use a chained list or dual // pointer, which ensures that no space is wasted, but the code is more complex
char save[100][1024];
i = 0; // clear 0, record how many lines **** there are in the back
while ((fgets(save[i], 1024, fp))) { // read the file in a loop until fgets(save[i], 1024, fp)) { // read the file in a loop until fgets(save[i], 1024, fp)) read the file in a loop until fgets returns NULL indicating it's done
i++;
}
printf("Please enter the contents of the data to be inserted:");
fgets(buf, 1024, stdin); // Receive the contents of the keyboard
// As the file pointer is pointing to the end of the file, it is not necessary for the file pointer to point to the end of the file after reading. file pointer points to the end of the file after reading it, it is relocated to the previously saved location
fseek(fp, offset, SEEK_SET);
fputs(buf, fp); // Write the data to be inserted
int j;
for (j = 0; j < i; j++) { // The data saved before, in order of the Save data, write backwards in order
fputs(save[j], fp);
}
return 0;
}