从函数中打开文件

时间:2012-04-06 22:46:16

标签: c function file-io

我正在做一件作业,我想把一个FILE *作为参数发送到函数中,因为我必须以相同的方式打开3个文件和一些“风味文本”。我这样做得很好:

enum {IN, STAT, REPRINT} FNAMES;
#define FNAME_MAX 256

int main(void)
{
  FILE *in, *stat, *reprint;
  char fnames[3][FNAME_MAX]; // store actual file names input by user
  char format[11];           // format identifier used in scanf for file names


  in = stat = reprint = NULL; // TODO: Check necessity

  buildFormat(format); // this translates FNAME_MAX into the string "%256s[^\n]"

  // TODO: Find out why this cannot be put into a function!
  // open the input file
  while (in == NULL)
  {
    // get input file name
    getFileName(format, fnames[IN]); // simply prompts for a file name/path

    // open the input file for reading
    in = fopen(fnames[IN], "r");

    // make sure it opened
    if (in == NULL)
      printf("%s did not open, please check spelling/path.\n\n", fnames[IN]);
    else
      printf("%s was opened successfully.\n\n", fnames[IN]);
  }
  return 0;
}

什么是行不通的:

void openFile(FILE *in, char *format, char *fname, char *openFor)
{
  // TODO: Find out why this cannot be put into a function!
  // open the input file
  while (in == NULL)
  {
    // get input file name
    getFileName(format, fname); // simply prompts for a file name/path

    // open the input file for reading
    in = fopen(fname, openFor); 

    // make sure it opened
    if (in == NULL)
      printf("%s did not open, please check spelling/path.\n\n", fname);
    else
      printf("%s was opened successfully.\n\n", fname);
  }
}

如果我把文件读取操作放在函数中它工作正常,但如果我回到main并尝试使用我发送的文件指针不起作用。

2 个答案:

答案 0 :(得分:2)

您希望openFile返回FILE *。从输入参数中删除FILE *in。将FILE *in声明为局部变量,并在完成后返回其值。

您可能还想在本地声明fname,除非您需要在openFile返回后使用它。

答案 1 :(得分:0)

C函数不会修改它们的参数,所以如果你真的希望函数修改FILE *,你可以添加一个indirection级别,就像在openFile中一样(FILE ** in ...并调用它丑陋,是的。更常见的做法就像其他答案所说的那样,返回指针......

在确保我的易错记忆电路使用正确的词语时发现了一个幽默的引用,“计算机科学中的所有问题都可以通过另一层次的间接解决” - 大卫惠勒