开发者

Continue the program only if the two files exist in C

开发者 https://www.devze.com 2023-04-12 04:06 出处:网络
#include <stdio.h> #include <st开发者_StackOverflow中文版dlib.h> void main() { int i,x;
#include <stdio.h>
#include <st开发者_StackOverflow中文版dlib.h>

void main()
{
    int i,x;

    FILE *fl1, *fl2;

    x = 0;

    for(i = 0; ; i++)
    {
        fl1 = fopen("file1","r");
        fl2 = fopen("file2","r");
        if(fopen("file1","r") == NULL && fopen("file2","r") == NULL)
        {
           x = x + 1;
        }
        else break;
    }

    printf("\n\nDONE!\n\n");
}

I have this code, I want it to print DONE only when the 2 files, file1 and file2 exist. But it seems that it is not working. When I create only file1 the program break, same if I only create file2.


since you store the return value of fopen() in fl1 and fl2 just compare these not being NULL.

fl1 = fopen("file1","r");
fl2 = fopen("file2","r");

if( fl1 != NULL && fl2 != NULL )
{
  printf( "\nDONE!" );
}


You are making a wrong test. fopen returns NULL if the file could not be opened. Your test should be more like:

if(fopen("file1","r") != NULL && fopen("file2","r") != NULL)

EDIT: Also for(i = 0; ; i++) is an infinite loop.


You should write

FILE *fin1 = fopen("file1", "r");
FILE *fin2 = fopen("file2", "r");
if (fin1 != NULL && fin2 != NULL)
{
    // Do your work
    fclose(fin1);
    fclose(fin2);
}
else
{
    // some file didn't open. Close the other possible open one and return error
    if (fin1)
        fclose(fin1);
    if (fin2)
        fclose(fin2);
    // give error;
}

Note the fclose part. It is important that you close the files you opened. For example for if you later want to open it again. In general, whatever resource you take from the operating system (for example memory, file, socket etc), it is your responsibility to return it.


The statement:

if(fopen("file1","r") == NULL && fopen("file2","r") == NULL)

will only be true if both files do not exist, leaving the other three cases (one exists, the other exists, or both exist) to be treated the same way.

If your intent is to simply output DONE if both exist, you can try:

#include <stdio.h>

int main (void) {
    FILE *fl1, *fl2;

    fl1 = fopen ("file1", "r");
    fl2 = fopen ("file2", "r");

    if (fl1 != NULL && fl2 != NULL)
        printf("DONE\n");

    if (fl1 != NULL) fclose (fl1);
    if (fl2 != NULL) fclose (fl2);
}

This also gets rid of your more, shall we say, ... colourful ... syntactic constructs :-)


If you just want to check if the files exist, rather than opening them, use access(), eg.

#include <unistd.h>

if (!access("file1", F_OK) && !access("file2", F_OK))
{
    /* Files exist, do something */
}
0

精彩评论

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

关注公众号