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

Posted

技术标签:

【中文标题】从文件读取数据时的无限循环【英文标题】:Infinity loop while reading data from file 【发布时间】:2015-08-12 17:49:21 【问题描述】:

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

代码:

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);
     

【问题讨论】:

见:***.com/questions/5431941/… 【参考方案1】:

我看到的问题。

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

改变

 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
 

【讨论】:

以上是关于从文件读取数据时的无限循环的主要内容,如果未能解决你的问题,请参考以下文章

使用后台并行无限循环 C# 读取缓冲区 [关闭]

从c中的文件读取数据

c ++处理来自输入文件的数据会创建无限循环

使用没有无限循环的 C++ i 检测文本文件中的更改?

读取循环时的Shell脚本仅执行一次

从管道读取的无限循环线程进入 timed_waiting