我正在编写一个程序,收集两个文件名的用户输入,并打开其中一个用于阅读,其中一个用于写入 .
我的代码:
void
gather_input (char* infileName, char* outfileName, char* mode,
FILE* inputFile, FILE* outputFile)
{ int flag = 0; //error checking flag
do
{ flag = 0;
printf("Enter the name of the source file: ");
scanf("%s", infileName);
if (!(inputFile = open_input_file(infileName))) //will enter if statement only if
{ fprintf(stderr, "Error opening '%s': %s\n", //inputFile == NULL
infileName, strerror(errno)); //some error checking
flag = 1; //true
}
} while (flag);
do
{ flag = 0;
printf ("Enter the name of the destination file: ");
scanf("%s", outfileName);
if (!(outputFile = open_output_file(outfileName)))
{ fprintf (stderr, "Error opening '%s': %s\n",
infileName, strerror(errno));
flag = 1;
}
} while (flag);
在错误检查输入文件被打开时工作正常;但是,它无法更正或检测输出文件是否已正确输入或打开 . 这是一个更大的函数的一部分,如果需要我可以发布(char *模式用于不同的部分) .
问题是,当我说fopen(outfileName,“w”),这是open_output_file()中发生的事情时,程序将尝试创建一个文件(如果一个文件不存在)(即,当用户提供垃圾输入时) . 我想避免这个 . 有任何想法吗?
2 回答
使用开放模式
"r+"
(读写) . C99标准的7.19.5.3/4:这意味着您需要对该文件具有读取权限 .
如果您使用POSIX,则可以使用
open
打开文件,然后使用fdopen
获取FILE*
以获取生成的文件描述符 .男人3 fopen
所以
"r+"
似乎是一个很好的候选人 .