Check file exist with File Descriptor in C

Hello Guys.. is there a way to check ONLY if a file exist?
I mean..
1
2
3
if((fd = open(PATH, O_CREAT | O_EXCL == -1) && (errno = EEXIST)){
    printf("File does not exist");
}

I use this code to check if file exist in Path.. but at the same time, it create the file :/
I just want to check if it exist and not create it if not...
Any suggestion?
Thanks..
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

bool exists( string filename )
{
   ifstream in( filename, ios::in );
   return in.good();
}

int main()
{
   string filename;
   cout << "Enter filename: ";   cin >> filename;
   cout << filename << ( exists( filename ) ? " exists" : " does not exist" ) << '\n';
}
lastchace


I’m programming in C.. with File Descriptor. I can’t use other Programming language or other structure.
Firstly, always post real code and not something you bashed in with a closed fist. :-)
Secondly, it's kind of a funny question asking how to not create the file when you are very clearly passing the "create" flag. Just don't pass it.

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <fcntl.h>

int main() {
    int fd;
    if ((fd = open("testfile", O_RDONLY)) == -1) {
        fprintf(stderr, "File does not exist\n");
        return 1;
    }
    return 0;
}

Last edited on
Topic archived. No new replies allowed.