c - 结构体作为外部函数 C 的参数

标签 c function structure extern

我必须使用这种结构读取文本文件。另外,我必须使用外部函数。我编写了文件读取代码,它在主函数中工作。

文本文件:

banana 3 orange 8 music 9- 第一个字符是空格*

#include <stdio.h>
#include <stdlib.h>

struct file
{
  char name[30];
  char size;
};


int main()
{
   int n=0;
   struct file f[30];
   FILE *files;
   files=fopen("files.txt","r");
   int n=0;
    while (1)
     {
      fgetc(files);
      if(feof(files)) break;
      fscanf(files,"%s %c",&f[n].name,&f[n].size);
      n++;
     }
}

但是当我尝试使用另一个 c 文件和外部函数进行读取时,它不起作用.. :(

这是在filereading.c中写的:

void fileReading(struct file *f[30], FILE *files)
{
  int n=0;
 while (1)
 {
   fgetc(files);
   if(feof(files)) break;
   fscanf(files,"%s %c",&f[n].name,&f[n].size);
   n++;
 }
}

和 fileReading.h:

void fileReading(struct fisier *, FILE *);

在 main.c 中:

#include <stdio.h>
#include <stdlib.h>

struct file
{
  char name[30];
  char size;
};


int main()
{
   int n=0;
   struct file f[30];
   FILE *files;
   files=fopen("files.txt","r");
   fileReading(f[30],files);
}

当我编译它时,它说:

request for member 'name' in something not a structure or union
request for member 'size' in something not a structure or union|
||=== Build finished: 2 errors, 2 warnings (0 minutes, 0 seconds) ===||

你能帮帮我吗?谢谢!

最佳答案

据我所知,您似乎对指针没有很好的理解。 这些更改应该可以解决您的问题:

void fileReading(struct file *f, FILE *files)
{
  int n=0;
 while (1)
 {
   fgetc(files);
   if(feof(files)) break;
   fscanf(files,"%s %c",f[n].name,&f[n].size);
   //printf("%s %c",f[n].name,f[n].size);
   n++;
 }
}
int main()
{
   int n=0;
   struct file f[30];
   FILE *files;
   files=fopen("files.txt","r");
   fileReading(f,files);
}

你做错了什么:

void fileReading(struct file *f[30], FILE *files)  //here you were saying file is a ** 
fscanf(files,"%s %c",&f[n].name,&f[n].size); // here you need to send the a char* but you were sending a char ** as a second parameter
fileReading(f[30],files); // here you were sending the 31th element of the structure array f which by the way doesn't exist (indexing is from 0 , f[29] is the last) even though that was not what you wanted to do in the first place

关于c - 结构体作为外部函数 C 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34707236/

相关文章:

c++ - GetSystemMetrics(SM_CYVIRTUALSCREEN) 返回不正确的高度?

c - 这个程序如何 self 复制?

matlab - 在 Matlab 中创建更复杂的数据结构?

c - C 中的嵌套结构

c++ - C++ 中的函数和变量声明

php - 编写代码流程图的建议

copy_from_user - 难以从用户空间复制双指针

代码块不在 linux lite 中编译空 c 文件

java - 返回值的三元运算符 - Java/Android

c++ - 为什么要使用 const 成员函数?