Search code examples
cstat

C - having trouble using stat() to get bytes


char string[50], s[50];
struct stat buf;
int counter = 0;

while (fgets(string, sizeof string, stdin)) {
    if (strspn(string, "size ") == 5) {
        for (int i = 5; i < strlen(string); i++) {
            s[counter] = string[i];
            counter++;
        }
        s[counter] = '\0';

        if (stat(s, &buf) < 0)
            return 1; //PROBLEM OCCURED

        printf("FILE: %s\n", s);
        printf("SIZE: %d\n", (int)buf.st_size);
    }
 }

The context of the program is not too important, but I am trying to use this because after "size " the name of the file is the only input. I then pass that into stat which is supposed to give me bytes of the given file if it exists. Ultimately, the program returns 1 every time like I am using stat wrong. Help please!


Solution

  • fgets() returns the trailing newline character(s), so your 'filename' is never correct.

    Replace:

    for(int i = 5; i < strlen(string); i++) {
       s[counter] = string[i];
       counter++;
    }
    s[counter] = '\0';
    

    with:

    char *source = &(string[5]), *dest = s;
    while((*source != 0) && (*source != 10) && (*source != 13)) {
       *dest++ = *source++;
    }
    *dest = 0;
    

    This way you are copying everything until a zero (end of string), or carriage return, or linefeed - rather than appending the CR and/or LF char to the string too.