I have 950 files and each file has 20k lines and 4 columns of data points. And I want to read
all column 0 and column 2 data points and store them into the array
for further use.
I've browsed through: Going through a text file line by line in C, Reading text file and storing columns in an array, Reading multiple text files in C, and How to read all files in a folder using C to understand how to read line by line with certain columnn and how to "scan" multiple files.
And I combined them to suit what I desire, the following code is to test to see whether my idea can work or not, so I just put 2 files into the directory:
#include <stdio.h>
#include <dirent.h>
int main ()
{
float w,x,y,z;
const char *dir = "C:\\Users\\ONG\\Desktop\\new";
struct dirent * entry;
DIR *d = opendir(dir);
FILE *fp;
if (d == 0)
{
perror("opendir");
return 0;
}
while ((entry = readdir(d)) != 0)
{
if((!strcmp(entry->d_name, ".")) || (!strcmp(entry->d_name, "..")))
{
continue;
}
printf("%s\n", entry->d_name);
fp = fopen(entry->d_name, "r");
fscanf(fp, "%f %f %f %f", &w, &x, &y, &z);
printf("%f %f\n", w, y);
fclose(fp);
}
closedir(d);
return 0;
}
To see the code work or not, I put 2 files into that directory. And the code is expected to print the file name followed by 2 data points (for example -0.049 0.576
), twice.
But what I get is:
2nd_testdata_point0.txt
818583905043582480000000000000000.000000 -1.#QNAN0
2nd_testdata_point1.txt
818583905043582480000000000000000.000000 -1.#QNAN0
What is the problem?
I have tried to use the exact code from the answer from How to read all files in a folder using C, and the error is the same as stated by the author. But I can't see how the suggestion in the comments solve the problem.