我可以确保当 fopen()-ing 为 "w"的文件时,程序不会创建文件吗?

标签 c

我正在编写一个程序来收集用户输入的两个文件名,然后打开其中一个进行读取,另一个进行写入。
我的代码:

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/

相关文章:

c - 为什么我的c程序突然用了30g的虚拟内存?

c - 如何将多个 .txt 文件读入单个缓冲区?

c++ - 是否可以将地址映射到函数的结果?

c - 不可靠的信号 API - 代码未按预期工作

java - 从 Java 代码调用 C 可执行文件后没有得到任何输出

c - OpenCV 2.3 中的 cvaux230d.lib 在哪里?

c - 调试联动警告 "type of symbol does not match original declaration"

C内存泄漏与valgrind

c - _dl_close 断言失败

c++ - 如何在 Arduino 中将字符串转换为 char *?