首页 文章

我可以确保当fopen()为“w”文件时,程序不会创建文件吗?

提问于
浏览
1

我正在编写一个程序,收集两个文件名的用户输入,并打开其中一个用于阅读,其中一个用于写入 .
我的代码:

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 回答

  • 3

    使用开放模式 "r+" (读写) . C99标准的7.19.5.3/4:

    如果文件不存在或无法读取,则打开具有读取模式的文件('r'作为模式参数中的第一个字符)将失败 .

    这意味着您需要对该文件具有读取权限 .

    如果您使用POSIX,则可以使用 open 打开文件,然后使用 fdopen 获取 FILE* 以获取生成的文件描述符 .

  • 4

    男人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+" 似乎是一个很好的候选人 .

相关问题