Search code examples
cfopenfwritefile-managementfile-manipulation

Reading data from files in C


So I have a big text file with data in it and I would like to rearrange it. The data has a combination of integers and floats per each line but I'm only interested in grabbing the first integer, which is either a 1 or 0, and putting it at the end of the line.

For example, in my data file, I have the following line
1 0.41 1 44
and I would like to be
0.41 1 44 1

This is what I have so far and can't get it to work right. Thanks.

void main() {
FILE *fp;
FILE *out;

char str[15];
char temp;

fp = fopen("dust.txt", "r+");
out = fopen("dust.dat", "w");

while(fgets(str, sizeof(str), fp) != NULL) {
    temp = str[0];
    str[strlen(str)] = ' ';
    str[strlen(str)+1] = temp;
    str[strlen(str)+2] = '\r';
    str[strlen(str)+3] = '\n';

fwrite(str, 1, strlen(str), out);
}   

fclose(fp);
    fclose(out);
}

Solution

  • This treats the output as a text file (same as input), not a binary. I've put code comments where appropriate. Your most serious error was in calling strlen after overwriting the string terminator. There is only need to call it once anyway.

    #include <stdio.h>
    #include <string.h>
    
    int main(void)  {                           // main must be type int
        FILE *fp;
        FILE *out;
        char str[100];                          // be generous
        size_t len;
    
        fp = fopen("dust.txt", "r");
        out = fopen("dust2.txt", "w");          // text file
        if(fp == NULL || out == NULL)
            return 1;
    
        while(fgets(str, sizeof(str)-3, fp) != NULL) {
            str [ strcspn(str, "\r\n") ] = 0;   // remove trailing newline etc
            len = strlen(str);
            str[len] = ' ';                     // overwrites terminator
            str[len+1] = str[0];                // move digit from front
            str[len+2] = 0;                     // terminate string
            fprintf(out, "%s\n", str + 2);      // write as text
        }   
    
        fclose(fp);
        fclose(out);
        return 0;
    }
    

    Input file:

    1 0.41 1 44
    0 1.23 2 555
    

    Output file:

    0.41 1 44 1
    1.23 2 555 0