0

I am a C beginner and I am a bit confused about how to do this. I am trying with readdir and strcmp functions but it throws me a lot of errors.

#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <dirent.h>

int main(int argc, char *argv[])
{   
    DIR *dirp;
    struct dirent *direntp;

    dirp = opendir(argv[1]);
    if (dirp == NULL)
    {
        printf("File could not be open\n");

        return -1;
    }

    int i = 0;
    while((direntp[i]=readdir(dirp)) != NULL)
    {
        if(strcmp(direntp[i], argv[2]) == 0)
        {
            printf("The file %d is in directory %s my friend!", argv[2], dirp);
        }

        i++;
    }

    closedir(dirp);
    return 0;
}
Bitmap
  • 12,402
  • 16
  • 64
  • 91
  • first you have to google your question and if you get any error then post your code and error list in your question. http://stackoverflow.com/q/230062/3184380 – Shell Feb 19 '14 at 11:15
  • Have a look at: [Similar Question](http://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform) – HvS Feb 19 '14 at 11:16
  • Also, Your directory content iterator sucks. In Your case, You should also check if the `direntp[i]` is actually a file - `if (direntp[i]->d_type == DT_REG) {}`. As I suggested some time ago [here](http://stackoverflow.com/a/17683417/1150918). – Kamiccolo Feb 19 '14 at 12:22

3 Answers3

4
read about access

if(access("myfile.txt", F_OK)) {
     // file exists
}
baliman
  • 588
  • 2
  • 8
  • 27
  • `int access(const char *path, int amode)` - Hence the first parameter is the entire file path. – HvS Feb 19 '14 at 11:21
0

try to open the file in read mode like this,

FILE *f;
f=fopen("file.txt","r");

if(f is not empty)
  //file exits
Balayesu Chilakalapudi
  • 1,386
  • 3
  • 19
  • 43
0
int main(int argc, char *argv[]){
    DIR *dirp;
    struct dirent *direntp;

    dirp=opendir(argv[1]);
    if (dirp == NULL){
        printf("File could not be open\n");
        return -1;
    }

    while((direntp=readdir(dirp)) != NULL){
        if(strcmp(direntp->d_name,argv[2]) == 0){
            printf("The file %s is in directory %s my friend!", argv[2], argv[1]);
            break;
        }
    }

    closedir(dirp);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70