首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我能确保,当fopen()为"w“打开一个文件时,程序不会创建文件吗?-ing()

我能确保,当fopen()为"w“打开一个文件时,程序不会创建文件吗?-ing()
EN

Stack Overflow用户
提问于 2010-11-17 06:21:54
回答 2查看 182关注 0票数 1

我正在编写一个程序,它收集用户对两个文件名的输入,并打开其中一个用于读取,另一个用于写入。

我的代码:

代码语言:javascript
复制
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()中发生的事情。我想避免这种情况。有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-17 06:32:56

man 3 fopen

代码语言:javascript
复制
``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+"似乎是一个很好的候选者。

票数 4
EN

Stack Overflow用户

发布于 2010-11-17 06:30:00

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

如果file不存在或无法读取,则使用读取模式('r‘作为模式参数中的first字符)打开file失败。

不过,这意味着您需要对该文件拥有读取权限。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4199660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档