简体   繁体   中英

Infinity loop while reading data from file

I'm trying to read data from file. There are three rows. What I've done is this below. Problem is that (file exists) it is infinity loop while reading a file. I've observed that program is not moving line by line until it reaches end of file. What's incorrect in my code?

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

Problems that I see.

  1. You are using the wrong format, %fl instead of %lf .
  2. You are not checking whether fscanf successfully read the data or not.

Change

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

to

 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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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