2016-03-23 15 views
-1

数组我有此格式的文本文件:阅读从文本文件的int到用C

100 0 10 1 
101 6 10 1 
102 8 4 1 
103 12 20 1 
104 19 15 1 
105 30 5 1 
106 35 10 1 

我需要把这些号码入阵列具有PID [],抵达[],突发[]和优先级[]。 C不是我最强的语言,所以我在做这件事时遇到了一些麻烦。

这里是我当前的代码:

void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]){ 
FILE *file; 
int i = 0; 
file = fopen("Process.txt", "r"); 

//File format is pID, arrival, bursts, and priority 
if (file){ 
    while (!feof(file)){ 
     pID[i] = fscanf(file, "%d ", &i); 
     arrival[i] = fscanf(file, "%d ", &i); 
     bursts[i] = fscanf(file, "%d ", &i); 
     priority[i] = fscanf(file, "%d ", &i); 
    } 
    fclose(file); 
} 

感谢您的帮助!

+0

[为什么 - 虽然feof文件总是错](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)。而且“我在做这件事上遇到了一些麻烦”并不是真的**具体*。见[问]。 – Olaf

+0

'fscanf'返回*成功扫描的项目数*,而不是扫描值。 'if(fscanf(file,“%d”,&pID [i])!= 1)exit(1);' –

+0

抱歉,放入数组的值不在文件附近。感谢这篇文章。如果!feof(文件)不正确,那么循环遍历文件的每一行的正确方法是什么? –

回答

1

您以错误的方式使用feoffscanf。我建议你一次从文件中读取一行,检查它是否被读取,然后从缓冲区中扫描值,并检查数组索引是否仍然正常,并扫描正确数量的字段。

void readFile(int n, int pID[], int arrival[], int bursts[], int priority[]) { 
    FILE *file; 
    int i = 0; 
    char buffer[100]; 
    file = fopen("Process.txt", "r"); 
    if (file){ 
     while (i < n && fgets(buffer, sizeof buffer, file) != NULL) { 
      if(sscanf(buffer, "%d%d%d%d", &pID[i], &arrival[i], &bursts[i], &priority[i]) != 4) { 
       exit(1);    // or recovery strategy 
      } 
      i++; 
     } 
     fclose(file); 
    } 
} 
+0

非常感谢!这解决了我的问题,所有事情都应该被读懂。 –

+0

所以sscanf行正在检查以确保文件的每一行中有四个值,同时也将相应的值放入数组中?对不起,我一直在问这么多问题,我只是想完全理解这是如何解决我的问题。 –

+0

是的,这是正确的。检查任何你可以检查的东西总是一个好主意:对于健壮的代码,不要做任何事情,特别是当输入源可能不在你的控制范围内时。虽然注意:如果有超过4个数字,它将简单地忽略该文本行中的任何其他数据,但它会*捕获任何不是数字的东西。 –