0

I have files something like this:

  • file1_a_etc.txt,
  • file1_b_etc.txt
  • file2_a_z.txt
  • file2_b_z.txt

I want to get the size of files with "a" i.e. file2_a_z.txt & file1_a_etc.txt

I have got a large number of files this way, so cant specify each name individually.

I am a beginner at C.
I know how to read the size of a single file. And I am working on windows.

#include <stdio.h>       
#include <sys/stat.h>   // For struct stat and stat()

struct stat attr;
void main()
{   
if(stat("filename.txt", &attr) == 0)
{

    float x;
    x=(attr.st_size)/1048576.0;             //1MB=1048576 bytes
    printf("Filesize: %.2f MB", x);
}
else
{
  // couldn't open the file
    printf("Couldn't get file attributes...");
}
}
itzcutiesush
  • 89
  • 1
  • 9

4 Answers4

1

For Windows console there is function _findfirst. For first parameter put *a*.txt.

i486
  • 6,491
  • 4
  • 24
  • 41
0

You need to iterate over the files in a given directory while searching for the substring in each file name.

This answer, under the section (Unix/Linux), specifies how to iterate over each filename while comparing for an exact match, you can modify the strcmp function call to strstr to look for a substring.

Community
  • 1
  • 1
0

You could make an Array of strings to store all filenames. Then you can use the strchr function to test, if an 'a' or other character is the name. The use of this function is explained e.g at http://www.tutorialspoint.com/ansi_c/c_strchr.htm

Kai
  • 103
  • 4
0

Reading directories programmatically can be done with readdir.

You could do something like this:

#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

static void lookup(const char *dir)
{
    DIR *dirp;
    struct dirent *dp;


    if ((dirp = opendir(dir)) == NULL) {
        perror("couldn't open '.'");
        return;
    }


    do {
        errno = 0;
        if ((dp = readdir(dirp)) != NULL) {
            if (strstr(dp->d_name, "_a_") == NULL)
                continue;


            (void) printf("found %s\n", dp->d_name);
            // Add code to handle the file
        }
    } while (dp != NULL);


    if (errno != 0)
        perror("error reading directory");
    (void) closedir(dirp);
    return;
}

readdir is part of POSIX.1-2001, which is supported by unix/linux-type systems (including OS/X) but only some windows compilers. If you are programming in windows you may have to use another solution.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82