2014-05-18 32 views
0

所以这只是一个简单的从文件循环读取,我似乎无法确定哪里出了问题。我已经尝试了很多方法,但似乎无法通过循环。我尝试了很多方法进入(最初使用getc,但getc整个循环将被忽略。)从文件循环读取 - 无法使用feof或getc进入循环

由于某种原因,它只是没有为我工作。下面的方式,程序冻结可能有人可以解释为什么这样,因为文件指针应该指向文件的开头,文件'input.txt'只是一个简单的数据列表,我应该读入一个结构,然后传递给另一个函数,输入到我的数据结构中。

但是,我似乎甚至不能去其他函数。花了几个小时试图解决这个问题的不同方式。肯定有一个明显的解决方案,我没有看到。

void readWrite(char *inFile) 
{ 
    FILE *fp; 
    FILE *fpBin; 
    char c; 
    stuBucket temprec; 
    long address; 

    //open binary file to initialize hash file 
    if ((fpBin = fopen(BINARYFILE, "w+b")) == NULL) 
    { 
     printf("Could not open binary file %s.\n", BINARYFILE); 
     return; 
    } 
    fwrite(fpBin, sizeof(struct student), 50, fpBin); //Write entire hash table to disk 
    if (fp = fopen(inFile, "r") == NULL)  //open text file to read in from 
    { 
     printf("Could not open input file %s.\n", inFile); 
     return; 
    } 
    printf("Input File %s Open.\n", inFile); 

在下面

while(!feof(fp)) 
    { 
     printf("hello"); 
     fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName, 
            temprec.firstName, &temprec.amount); 
     writeRecord(temprec); 
     insert(temprec, fpBin); //hash data to disk 
     printf("insert done\n"); 
    } 
    fclose(fp); 
    fclose(fpBin); 
}//end readFromFile 

备用while循环问题,而被跳过的input.txt中

6745 SMITH ANNA 7769.87 
5675 JOHNSON SHEILA 23.91 
1235 WILLIAMS JANE 93.12 
2341 JONES BARBARA 74.23 
8624 BROWN YELENA 56.75 
9162 DAVIS SUSAN 902.34 
7146 MILLER ALISON 8934.12 
2328 WILSON ROYCE 123.09 
1622 MOORE TONI 83.65 
1832 TAYLOR JOAN 293.18 
3271 GARCIA ROBERT 43.72 
4717 MARTINEZ JHON 85.11 
9345 ROBINSON ANDRE 15.67 
1623 CLARK VICTOR 83.45 
5673 HALL MARC 93.13 
6275 ALLEN RAY 958.34 
5392 HERNANDEZ MICHAEL 23.45 
+0

请编辑该问题,并添加示例'inFile'的几行。 –

+4

1)将'char c;'改为'int c;'2)feof()不会做你想做的事情,最好暂时避免它。 – wildplasser

+0

@MahonriMoriancumer完成。只是提醒所有人:我甚至不能进入循环。这是主要问题,而不是实际循环的内容 - 虽然它可能有错误我可以处理。 – lloyd

回答

2

你的一个问题是:

if (fp = fopen(inFile, "r") == NULL) 

应该(当然)是:

if ((fp = fopen(inFile, "r")) == NULL) 

这则匹配在哪里打开二进制文件。

+0

就是这样。在使用作业时,我并不知道括号的确切用法。对我来说,这是一种新的语法,因为到目前为止,我一直在不同的线路上进行操作。谢谢。 – lloyd

1

c = getc(fp); 
while(c != EOF) 
{ 
    ungetc(c, fp); 
    printf("hello"); 
    fscanf(fp, "%d %s %s %f\n", temprec.stuID, temprec.lastName, 
           temprec.firstName, &temprec.amount); 
    writeRecord(temprec); 
    insert(temprec, fpBin); //hash data to disk 
    printf("insert done\n"); 
    c = getc(fp); 
} 

内容在这种情况下,可以fscanf留下一些文件末尾的空格字符。一定要检查多少个值通过的fscanf成功读取:

if (fscanf(fp, "%d %s %s %d\n", ...) != 4) break;