2

I'm writing a program where I need to print all the files in a given folder and store the content of the files in order to compare it to another string. What I have now is:

while ((ent = readdir(dir)) != NULL)
        {
            if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
            {
                // do nothing (straight logic)
            }
            else {

                file_name = ent->d_name;
                printf("%s\n", file_name);
                file_name = ent->d_name;
            printf("%s\n", file_name);
            char *fd = file_name;
            struct stat *buf;
            buf = malloc(sizeof(struct stat));
            stat(fd, buf);
            int size = buf->st_size;
            printf("%d", size);
            }
        }

edit: my problem now is that it prints the size as negative

0xmarsh
  • 51
  • 5
  • http://stackoverflow.com/questions/8149569/scan-a-directory-to-find-files-in-c . Take a look at this post, it might help you. – RPT May 19 '17 at 20:42
  • Possible duplicate of [scan a directory to find files in c](http://stackoverflow.com/questions/8149569/scan-a-directory-to-find-files-in-c) – Seek Addo May 19 '17 at 21:07
  • not exactly. specifically, I have a folder wich contains 2 png. I need to open each in binary mod and compare every one of them to another string I already have – 0xmarsh May 19 '17 at 21:20

1 Answers1

0
  1. use strstr() to see if the filename ends with .png
  2. for files that don't match, skip to the next file
  3. for files that match, use stat() to get the file size
  4. use malloc() to allocate a buffer of sufficient size to read in the file
  5. use fopen() and fread() to read the entire file into the buffer
  6. use memcmp() to compare the file contents to the string you already have

As an alternative you could use glob() instead of readdir() and manually matching against ".png" with strstr.

bstpierre
  • 30,042
  • 15
  • 70
  • 103
  • You missed the point of 3 and 4. You don't need to malloc a buffer to hold `struct stat` -- just declare it the object (not a pointer) on the stack and pass a pointer to the object to `stat()`. Also you need to check the return value from `stat()` -- it is returning an error which is why you're getting a negative value for the size. You need to pass the path to the file, which includes the directory. You can construct a path string by using `snprintf()` with a stack buffer and passing in the dir name and the file name. – bstpierre May 20 '17 at 21:52