我正在做一份作业,我想将 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 并尝试使用我发送的文件指针它不起作用。