C 结构与功能
我已经声明了这样一个结构C 结构与功能,c,function,struct,C,Function,Struct,我已经声明了这样一个结构 typedef struct fileProperties //the struct. { char name[256]; /*File or directory name*/ int mode; /*protection and file type*/ int userId; /*User ID of owner*/ int groupId; /*Group ID of owner*/ int size; /*
typedef struct fileProperties //the struct.
{
char name[256]; /*File or directory name*/
int mode; /*protection and file type*/
int userId; /*User ID of owner*/
int groupId; /*Group ID of owner*/
int size; /*file size in bytes*/
char modifyTime[50]; /*modify time as a string*/
} FILES;
int createStruct()
{
char structBuffer[251];
printf("\n > Please enter a file name to create a struct for.> ");
inputFix(structBuffer, STRUCT_SIZE);
strncpy(file1.name, structBuffer, sizeof(structBuffer));
printf(" > Created.");
return 0;
}
我想在这样的函数调用中写入file1的属性
typedef struct fileProperties //the struct.
{
char name[256]; /*File or directory name*/
int mode; /*protection and file type*/
int userId; /*User ID of owner*/
int groupId; /*Group ID of owner*/
int size; /*file size in bytes*/
char modifyTime[50]; /*modify time as a string*/
} FILES;
int createStruct()
{
char structBuffer[251];
printf("\n > Please enter a file name to create a struct for.> ");
inputFix(structBuffer, STRUCT_SIZE);
strncpy(file1.name, structBuffer, sizeof(structBuffer));
printf(" > Created.");
return 0;
}
其中inputFix是:
void inputFix(char string[],int length)
{
int ch, len = 0;
fgets(string, length, stdin);
string[strcspn(string, "\r\n")] = '\0';
len = strlen(string);
if (len == length - 1)
{
while((ch = getchar()) != '\n' && ch != EOF);
}
}
STRUCT_SIZE定义为250的大小
在我的代码顶部,我有这样一句话
FILES file1;
我已经阅读了一些有关编码单元和结构的教程
我不明白为什么会出现错误:
functions.c:59:3: error: unknown type name ‘FILES’
functions.c:62:52: error: request for member ‘name’ in something not a structure or union
不值得使用typedef吗?我是否遗漏了与使用structs相关的内容,如果是,请链接到另一个类似的问题
这可能与此程序被分成2个文件main.c函数有关。c&h。我是否需要在链接器文件中包含结构?main.c只调用createStruct()。我假设变量
文件file1
的定义在main.c
中,而函数createStruct
在文件函数.c
中。在这种情况下,您需要:
extern FILES file1;
并将其包含在functions.c
的开头。否则,编译器不知道另一个文件中定义了变量file1
因此,您的header.h
将如下所示:
typedef struct fileProperties //the struct.
{
char name[256]; /*File or directory name*/
int mode; /*protection and file type*/
int userId; /*User ID of owner*/
int groupId; /*Group ID of owner*/
int size; /*file size in bytes*/
char modifyTime[50]; /*modify time as a string*/
} FILES;
extern FILES file1;
您的main.c
将如下所示:
#include "header.h"
FILES file1;
...
而您的函数.c
将如下所示
#include "header.h"
int createStruct()
{
...
strncpy(file1.name, structBuffer, sizeof(structBuffer));
...
在
文件1之前是否有#include
行代码>行?好的,在我的代码顶部--你是指定义结构之前的文件file1
行吗?类型定义应该在.h
文件中。.h
文件的#include
行必须在声明结构之前。在#include之后,我有文件文件1。您的代码刚刚编译好。不确定您在哪里声明了“fileProperties”。我在“.c”文件中声明了所有。“在我的代码顶部有一条语句。”。这可能是个问题吗?在上面键入定义的文件属性的位置?仅当他有多个链接在一起的对象文件时才需要此选项。文件files1在functions.c和.h中声明,createStruct()在functions.cy中。您需要在头文件中以及在外部文件file1
之前定义结构。每个C文件都在一个编译器过程中编译,所以当从头到尾读取文件时,必须在此点之前声明给定点所需的所有内容。