我有以下代码片段:
struct stat *fileData;
if((fd=open("abc.txt",O_RDONLY)==-1)
perror("file not opened");
if((fstat(fd,fileData)==-1)
perror("stucture not filled");
printf("%d",fileData.st_size);
它向我显示错误:
request for member ‘st_size’ in something not a structure or union
我也尝试过使用stat
。
目前,您正在向未初始化的指针写入(fstat
是),然后尝试从中读取,就好像它是struct stat
一样。您应该将代码更改为:
struct stat fileData;
if((fstat(fd, &fileData) == -1)
^
或者,您可以将malloc
内存转换为fileData
,然后使用fileData->st_size
。这将不那么优雅(您必须使用free
等)。
您的fileData
结构是一个指针。fileData.st_size
必须是fileData->st.size
或(*fileDate).st_size
然而,stat()希望您为结构stat提供存储,您必须执行
struct stat fileData; // <---change to this
if((fd=open("abc.txt",O_RDONLY)==-1)
perror("file not opened");
if((fstat(fd,&fileData)==-1) // <---change to this
perror("stucture not filled");
printf("%d",fileData.st_size);