Current location - Loan Platform Complete Network - Big data management - LINUX C language, in the text of a line to insert content, preferably with a program.
LINUX C language, in the text of a line to insert content, preferably with a program.
This can not be directly inserted, because the data stored in the file is stored in order, you insert the data will be overwritten by the content of the back, only the insertion point location behind the data are read out and stored, and then inserted in the file pointer you want to write data, and then finally write your saved data to the file, in order to achieve the real insertion to the file.

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;

}