开发者

C Programming fopen() while opening a file

I've been wondering about this one. Most books I've read shows that when you open a file and you found that the file is not existing, you should put an error that there's no such file then exit the system...

FILE *stream = NULL; 
stream = fopen("student.txt", "rt");
if (stream==NULL) {
    printf(“Cannot open input file\n”);
    exit(1);
else {printf("\nReading the student list directory. Wait a moment please...");

But I thought that instead of doing that.. why not automatically create a new one when you found that the file you are opening is not existing. Even if you will not be writing on the file upon using the program (but will use it next time). I'm not sure if this is efficient or not. I'm just new here and have no programming experience wha开发者_JAVA技巧tsoever so I'm asking your opinion what are the advantages and disadvantages of creating a file upon trying to open it instead of exiting the system as usually being exampled on the books.

FILE *stream = NULL; 
stream = fopen("student.txt", "rt");
     if (stream == NULL) stream = fopen("student.txt", "wt");
     else {
          printf("\nReading the student list directory. Wait a moment please...");

Your opinion will be highly appreciated. Thank you.


Because from your example, it seems like it's an input file, if it doesn't exist, no point creating it.

For example if the program is supposed to open a file, then count how many vowels in it, then I don't see much sense of creating the file if it doesn't exist.

my $0.02 worth.


Argument mode:

 ``r''   Open text file for reading. 
 ``r+''  Open for reading and writing. 
 ``w''   Truncate file to zero length or create text file for writing.
 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  
 ``a''   Open for writing.  The file is created if it does not exist.
 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  

Your question is a simple case. Read above description, when you call fopen(), you should decide which mode shall be used. Please consider why a file is not created for "r" and "r+", and why a file is truncated for "w" and "w+", etc. All of these are reasonable designs.


If your program expects a file to exist and it doesn't, then creating one yourself doesn't make much sense, since it's going to be empty.

If OTOH, your program is OK with a file not existing and knows how to populate one from scratch, then it's perfectly fine to do so.

Either is fine as long as it makes sense for your program. Don't worry about efficiency here -- it's negligible. Worry about correctness first.


You may not have permission to create/write to a file in the directory that the user chooses. You will have to handle that error condition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜