我正在尝试创建一个函数,打开一个文件以便在C中读取

时间:2014-01-31 04:14:41

标签: c file function

我正在尝试创建一个可以打开文件进行阅读的功能。以下是我的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>

//char* readRecord(char individual);
void openfile(FILE peoplefile);

int main (int argc, char *argv[])
{
  char *lname = (char *)malloc(25*sizeof(char));


  if (argc < 2)
    {
      printf("\n\nUsage: %s <name>\n\n", argv[0]);
      exit (-1);
    }
  else
    {
      strcpy(lname, argv[1]);  //copies the last name from the command line int \
      variable lname
      printf("Your last name is %s\n",lname);
    } 

  FILE *peoplefile;
  openfile(peoplefile);

  while(!feof(peoplefile))
    {
      printf("Hi\n");
    }
 return 0;
}


void openfile(FILE peoplefile)
{
  peoplefile = fopen("./people.dat", "r");
  if(peoplefile == NULL)
    {
      printf("Error opening people.dat file\n\n");
    }
}

这些是我编译代码时遇到的错误:

prog1.c: In function `int main(int, char**)':
prog1.c:34: error: expected primary-expression before "peoplefile"
prog1.c: In function `void openfile(FILE)':
prog1.c:47: error: no match for 'operator=' in 'peoplefile = fopen(((const char*)"./people.dat"), ((const char*)"r"))'
/usr/include/stdio_impl.h:30: note: candidates are: __FILE& __FILE::operator=(const __FILE&)
prog1.c:48: error: no match for 'operator==' in 'peoplefile == 0'

3 个答案:

答案 0 :(得分:0)

void openfile(FILE peoplefile)
{
  peoplefile = fopen("./people.dat", "r");

那是错的。 fopen返回指向FILE的指针,即FILE*。如果你需要为调用者设置参数,那么你需要添加另一个间接级别,因为参数是通过C中的值(copy)传递的,所以......

int openfile(FILE **peoplefile)
{
    if (!peoplefile) return 1;
    *peoplefile = fopen(...);
    /* ... */
}

我更喜欢只返回FILE*的函数,然后你的整个openfile函数毫无意义;只需直接调用fopen,无需包装它。在main中,只需使用:

peoplefile = fopen("./people.dat", "r");
if (!peoplefile) {
    print_some_error();
    return 1;
}

您的代码也包含错误;如果您无法打开文件,则会打印错误消息,但仍然继续使用文件句柄!

答案 1 :(得分:0)

而不是

openfile(peoplefile);

我用

peoplefile = fopen("filename", "r")

将“filename”替换为您尝试打开以供阅读的文件名。

答案 2 :(得分:-2)

您也可以更改

//char* readRecord(char individual);
void openfile(FILE peoplefile);

//char* readRecord(char individual);
void openfile(FILE *peoplefile);

并实施如下

void openfile(FILE *peoplefile)
{
 peoplefile = fopen("./people.dat", "r");
if(peoplefile == NULL)
{
  printf("Error opening people.dat file\n\n");
}
}