我正在编写一个程序,它收集用户对两个文件名的输入,并打开其中一个用于读取,另一个用于写入。
我的代码:
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()中发生的事情。我想避免这种情况。有什么想法吗?
发布于 2010-11-17 06:30:00
使用开放模式"r+" (读写)。7.19.5.3/4的C99标准:
如果file不存在或无法读取,则使用读取模式('r‘作为模式参数中的first字符)打开file失败。
不过,这意味着您需要对该文件拥有读取权限。
如果您使用的是POSIX,则可以使用open打开文件,然后使用fdopen获取结果文件描述符的FILE*。
https://stackoverflow.com/questions/4199660
复制相似问题