从文件读取数据时无限循环

时间:2015-05-29 18:34:48

标签: c iostream

我正在尝试从文件中读取数据。有三排。我所做的就是下面的内容。问题是(文件存在)它在读取文件时是无限循环。我观察到程序在到达文件末尾之前不会逐行移动。我的代码中有什么不正确的?

CODE:

if (desktops == NULL) {
        printf("\n No such file.\n");
    } else{
            printf("\nFile exists. Reading\n");

        while(!feof(desktops)){

            if(numberOfObjects== 0)
            {
                 fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n",&height,&length,&width,&processorClock,&idNumberSerial,&processorTypeChars,&nameInNetworkChars,&ID);
                 nameInNetwork = string(nameInNetworkChars);
                 processorType = string(processorTypeChars);
                // nameInNetwork = "test";
                 glowaListyObjektow = new Desktop(height,length,width,processorClock,idNumberSerial,processorType,nameInNetwork,ID);
                 iterator = glowaListyObjektow;


                 iterator->previousObject = NULL;
                 iloscObiektow++;
                 nameInNetwork.clear();
                 processorType.clear();
            }
            else if(numberOfObjects> 0)
            {
                fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n",&height,&length,&width,&processorClock,&idNumberSerial,&processorTypeChars,&nameInNetworkChars,&ID);
                nameInNetwork = string(nameInNetworkChars);
                processorType = string(processorTypeChars);
                // nameInNetwork = "test";
                iterator->nextObject = new Desktop(height,length,width,processorClock,idNumberSerial,processorType,nameInNetwork,ID);


                iterator->nextObject->previousObject = iterator;
                iterator = iterator->nextObject;
                iloscObiektow++;
                 nameInNetwork.clear();
                 processorType.clear();
                // nameInNetworkChars = NULL;
            }



            cout<<"reading line"<<endl;
// Here line above is printed infinitely.
        }
            fclose(desktops);
    } 

1 个答案:

答案 0 :(得分:0)

我看到的问题。

  1. 您使用的格式错误,%fl而不是%lf
  2. 您没有检查fscanf是否成功读取了数据。
  3. 更改

     fscanf(desktops,"%fl %fl %fl %fl %d %s %s %d\n", &height, &length, &width, &processorClock, &idNumberSerial, &processorTypeChars, &nameInNetworkChars, &ID);
    

     int n = fscanf(desktops,"%lf %lf %lf %lf %d %s %s %d\n", &height, &length, &width, &processorClock, &idNumberSerial, &processorTypeChars, &nameInNetworkChars, &ID);
     if ( n != 8 )
     {
        // Deal with error condition
     }