简体   繁体   中英

read a file .txt in a C program

I am programing a parallel openmp in C language and I using this code to read one million of data from a .txt file.

 FILE *data = NULL;
 data = fopen("1millon.txt","r");

float ID, n, cord[1000000],cordy[1000000];
int ale = 1000000;  
for(i=0;i<ale;i++){

fscanf (data, "%f %f", &ID, &n);
    cordx[i]=ID;
    cordy[i]=n;
} 

Actually this "fscanf" is doing well when I run my program in my normal computer. But if I would like to run it in a cluster for parallelization it will show me the next warning ( warning: ignoring return value of 'fscanf', declared with attribute warn_unused_result [-Wunused-result] fscanf (data, "%f %f", &ID, &n); ) and it won't run."

Do you know another way how to read a .txt file instead of "fscanf", "fread"?

Thanks

fscanf() returns something. It is supposed to help you detect problems and special situations. Your cluster is configured to complain about that. Your own PC is not configured like that, hence it does not warn.

In order to avoid the warning on the cluster, do not ignore the return value. Ie check whether you successfully matched.

Alternatively do (void) fsanf... which tells the compiler "I intentionally ignore the helpful return value.".

According to the opengroup fscanf manpages (within the RETURN VALUE section), you should expect your call to fscanf to return 2 when it's successful at reading your two float values:

Upon successful completion, these functions return the number of successfully matched and assigned input items; this number can be 0 in the event of an early matching failure.

If it returns less than two, extra work will be required to discard erroneous input (see below for a nice example of this), exit the process or otherwise handle the error in some other manner. Otherwise, your future calls to fscanf will fail due to the same garbage left unread from stdin .

if (fscanf(data, "%f %f", &ID, &n) != 2) {
    fscanf(data, "%*[^\n]"); // read and discard up to the next newline character
    fgetc(data);             // ... and discard the newline character, too
    /* XXX: What to do with cordx[i] and cordy[i]? */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM