简体   繁体   中英

trouble with fscanf when using structs

typedef struct computer
{
char serialNumber[8];
int price;
int GBofRAM;
int GBofHardDrive;
}Computer;

Computer* readComputers(char* filename);


int main(int argc, char** argv) {

if(argc!=2){
    printf("Invalid number of arguments");
    return 1;
}
Computer* x=readComputers(argv[1]);
printComputers(x);

free(x);
return (EXIT_SUCCESS);
}
Computer* readComputers(char* filename)
{

Computer* cptr=malloc(sizeof(Computer)*6);
FILE* fp=fopen(filename, "r");
if(fp==NULL){
    printf("Failed to open file %s", filename);
    return;
}
//fread(cptr, sizeof(Computer), 6, fp);

fscanf(fp,"%s, %d, %d, %d", Computer->serialNumber, &Computer->price, &Computer->GBofRAM, &Computer->GBofHardDrive);

fclose(fp);  
return cptr;

I'm having issues getting this fscanf() to work correctly. it's saying it's missing an expression before Computer->serialNumber but I'm not sure why that's the case? I've tried looking on Tutorialspoint but that wasn't of too much help.

As per your code,

Computer->serialNumber

is an invalid statement. Computer here is a (user defined) data type. You cannot defererence that. You need to use cptr as the variable name, which you have defined.

Also, always check for the success of malloc() before using the returned pointer. Otherwise, in case if malloc() fails you'll be invoking undefined behavior by accessing invalid pointer.

In function Computer* readComputers(char* filename)

Computer* cptr=malloc(sizeof(Computer)*6);

You have pointer to struct cptr use it to access struct's members .

Write fscanf like this-

while(fscanf(fp,"%7s, %d, %d, %d", 
        cptr->serialNumber, &cptr->price, &cptr->GBofRAM, &cptr->GBofHardDrive)==4){
       // do something with these variables
   }         //loop as OP has mentioned in comment

Also checking return of fscanf .

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