Geoff
Geoff

Reputation: 53

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.

Upvotes: 0

Views: 133

Answers (2)

ameyCU
ameyCU

Reputation: 16607

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.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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.

Upvotes: 4

Related Questions