我正在编写一个程序来收集用户输入的两个文件名,然后打开其中一个进行读取,另一个进行写入。
我的代码:
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() 中发生的事情,如果文件不存在,程序将尝试创建一个文件(即,当用户提供垃圾时输入)。我想避免这种情况。有什么想法吗?
最佳答案
男人 3 fopen
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
``w'' Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
所以 "r+"
似乎是个不错的选择。
关于我可以确保当 fopen()-ing 为 "w"的文件时,程序不会创建文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4199660/