cfilefreadstdio

Read txt file by using fread() function


In this code I am trying to read all the data from the file using the fread() function. The problem is that nothing is read in the array. How can fix the error?

#include <stdio.h>

void func(const char *srcFilePath)
{
    FILE *pFile = fopen(srcFilePath, "r");
    float daBuf[30];
   
    if (pFile == NULL)
    {
        perror(srcFilePath);
    } else {
        while (!feof(pFile)) {
            fread(daBuf, sizeof(float), 1, pFile);
        }
    }
    for (int i = 0; i < 5; i++) {
        printf(" daBuf  = %f \n", daBuf[i]);
    }
}

void main() {
    const char inputfile[] = "/home/debian/progdir/input";
    func(inputfile);
}

The input file has values like this:

1.654107,
1.621582,
1.589211,
1.557358,
1.525398,
1.493311,
1.483532,
1.483766,
1.654107,

Solution

  • Your file contains formatted text, so you can use fscanf.

    Ensure that you are reading data into a new position in the array every iteration, and that you do not go beyond the bounds of the array.

    Use the return value of fscanf to control your loop.

    Notice the format string for fscanf is "%f,".

    #include <stdio.h>
    
    #define BUFMAX 32
    
    void func(const char *srcFilePath)
    {
        FILE *pFile = fopen(srcFilePath, "r");
    
        if (!pFile) {
            perror(srcFilePath);
            return;
        }
    
        float daBuf[BUFMAX];
        size_t n = 0;
    
        while (n < BUFMAX && 1 == fscanf(pFile, "%f,", &daBuf[n]))
            n++;
    
        if (ferror(pFile))
            perror(srcFilePath);
    
        fclose(pFile);
    
        for (size_t i = 0; i < n; i++)
            printf("daBuf[%zu] = %f\n", i, daBuf[i]);
    }
    
    int main(void)
    {
        const char inputfile[] = "/home/debian/progdir/input";
    
        func(inputfile);
    }
    
    daBuf[0] = 1.654107
    daBuf[1] = 1.621582
    daBuf[2] = 1.589211
    daBuf[3] = 1.557358
    daBuf[4] = 1.525398
    daBuf[5] = 1.493311
    daBuf[6] = 1.483532
    daBuf[7] = 1.483766
    daBuf[8] = 1.654107
    

    fread is generally intended for binary data, in which case you would open the file with the additional "b" mode.

    Here is an example, if your file contained binary data:

    #include <stdio.h>
    
    #define BUFMAX 32
    
    void func(const char *srcFilePath)
    {
        FILE *pFile = fopen(srcFilePath, "rb");
    
        if (!pFile) {
            perror(srcFilePath);
            return;
        }
    
        float daBuf[BUFMAX];
        size_t n = fread(daBuf, sizeof *daBuf, BUFMAX, pFile);
    
        if (ferror(pFile))
            perror(srcFilePath);
    
        fclose(pFile);
    
        for (size_t i = 0; i < n; i++)
            printf("daBuf[%zu] = %f\n", i, daBuf[i]);
    }
    
    int main(void)
    {
        const char inputfile[] = "/home/debian/progdir/input";
    
        func(inputfile);
    }