Home > database >  How can I make this operations with a file in C?
How can I make this operations with a file in C?

Time:10-17

I have this file that has just numbers:

0 1 2 3 4 5
5 6 7 8 9 10

I've made this function to write into the file:

void change(char* file) {

    int count = 0;
    FILE* arquive = fopen (file,"a ");

    char line[256];
    memset(line,0,strlen(line));
    char auxLine[256];
    memset(auxLine,0,strlen(auxLine));

    while (fgets(line, sizeof(line), arquive) != NULL) {
        if (count == 1) {
            memset(auxLine,0,strlen(auxLine));
            strncpy(auxLine, line, sizeof line);
            fprintf(arquive, "%s", auxLine);
        } else {
            count  ;
        }
    }

}

The output on the file:

5 6 7 8 9 105 6 7 8 9 10
10
    2   10
    2   10
9   9                                                                                                                                                                                                                                                          16   16    NULL NULL NULL NULL 

But whenever I try to append a string to the file using fprintf, it prints a lot of trash. I've tried using memset to clean whats inside, but without any success.

Thanks for your help!

CodePudding user response:

  1. fopen(..., "a ") -- Open for reading and writing. The stream is positioned at the end of the file. So, your while loop is never entered.

  2. The copies and memsets are meaningless, the code below is equivalent:

void change(char* file) {

    int count = 0;
    FILE* arquive = fopen (file,"a ");

    char line[256];

    while (fgets(line, sizeof(line), arquive) != NULL) {
        if (count == 1) {
            fputs(line, arquive);
        } else {
            count  ;
        }
    }

}
  1. The version below is probably closer to what you want:
void change(char* file) {

    int count = 0;
    FILE* arquive = fopen (file,"a ");
    FILE *src     = fopen(file, "r");
    char line[256];

    while (fgets(line, sizeof(line), src) != NULL) {
        if (count == 1) {
            fputs(line, arquive);
        } else {
            count  ;
        }
    }
    fclose(src);
    fclose(arquive);
}
  1. You may be playing with fire reading and writing the file you are appending. But it seems to work for small files at least.
  • Related