开发者

Can I ensure that, when fopen()-ing a file for "w", the program doesn't create a file?

I'm writing a program that gathers user input for two file names, and opens one of them for reading and one of them for writing.

My code:

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);

w开发者_运维问答orks fine on error-checking that the input file was opened; however, it fails to correct or detect that the output file was correctly entered or opened. This is part of a larger function, which I can post if needed (char* mode is used in a different section).

The problem is that when I say fopen(outfileName, "w"), which is what's happening in open_output_file(), the program will attempt to create a file if one doesn't exist (i.e., when the user gives garbage input). I want to avoid this. Any ideas?


man 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.

So "r+" seems like a good candidate.


Use open mode "r+" (reading and writing). 7.19.5.3/4 of the C99 standard:

Opening a file with read mode ('r' as the first character in the mode argument) fails if the file does not exist or cannot be read.

This means you need read permission on the file, though.

Failing that if you're on POSIX you can use open to open the file, then fdopen to get a FILE* for the resulting file descriptor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜