简体   繁体   English

使用结构时fscanf出现问题

[英]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. 我在使此fscanf()正常工作时遇到问题。 it's saying it's missing an expression before Computer->serialNumber but I'm not sure why that's the case? 这是说它在Computer->serialNumber之前缺少一个表达式,但是我不确定为什么会这样吗? I've tried looking on Tutorialspoint but that wasn't of too much help. 我尝试过在Tutorialspoint上查找,但这并没有太大帮助。

As per your code, 根据您的代码,

Computer->serialNumber

is an invalid statement. 是无效的陈述。 Computer here is a (user defined) data type. 这里的Computer是(用户定义的)数据类型。 You cannot defererence that. 您不能屈服于此。 You need to use cptr as the variable name, which you have defined. 您需要使用cptr作为已定义的变量名称。

Also, always check for the success of malloc() before using the returned pointer. 另外,在使用返回的指针之前,请始终检查malloc()是否成功。 Otherwise, in case if malloc() fails you'll be invoking undefined behavior by accessing invalid pointer. 否则,如果malloc()失败,您将通过访问无效指针来调用未定义的行为。

In function Computer* readComputers(char* filename) 在功能Computer* readComputers(char* filename)

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

You have pointer to struct cptr use it to access struct's members . 您有指向struct cptr指针,使用它可以访问struct的cptr

Write fscanf like this- 像这样写fscanf

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 . 同时检查fscanf返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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