简体   繁体   English

在C程序中读取文件.txt

[英]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. 我正在用C语言编写并行的openmp程序,并使用此代码从.txt文件读取一百万个数据。

 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. 实际上,当我在普通计算机上运行程序时,此“ fscanf”运行良好。 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." 但是,如果我想在集群中运行它以进行并行化,它将向我显示下一个警告(警告:忽略使用属性warn_unused_result [-Wunused-result] fscanf声明的'fscanf'返回值(数据,“%f%f “,&ID,&n);) ,它将无法运行。”

Do you know another way how to read a .txt file instead of "fscanf", "fread"? 您知道另一种方法来读取.txt文件而不是“ fscanf”,“ fread”的方法吗?

Thanks 谢谢

fscanf() returns something. fscanf()返回一些信息。 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. 您自己的PC并非如此配置,因此不会发出警告。

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.". 或者,执行(void) fsanf... ,它告诉编译器“我故意忽略了有用的返回值。”。

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: 根据opengroup fscanf联机帮助页 (在“ 返回值”部分内),当成功读取两个float值时,您应该期望对fscanf的调用返回2:

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. 如果早期匹配失败,此数字可以为0。

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 . 否则,由于未从stdin相同的垃圾,您将来对fscanf调用将失败。

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]? */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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