0
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!

Jordan
  • 2,070
  • 6
  • 24
  • 41
  • 1
    What does `s` contain right before the `stat` call? – Joey Adams Jun 05 '12 at 00:48
  • 3
    `strspn` doesn't do what you think. Use `strstr` instead. – Kerrek SB Jun 05 '12 at 00:52
  • I don't think that is a problem. I am looking for "size " and when that occurs I am getting the input thereafter. It may not be the best, but it is working for other functions I have going. – Jordan Jun 05 '12 at 00:54
  • 2
    You should consider replacing `return 1` with something like `perror("stat"); return 1;` (or hidden behind whatever `#ifdef DEBUG` you may wish..) to give you a useful error message to debug with. – sarnold Jun 05 '12 at 00:58

2 Answers2

2

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.

jka6510
  • 826
  • 5
  • 8
0

I guess the underlying problem exists in the usage of strspn(). The return value of strspn() can be determined from

if all of the characters in str1 are in str2, the function returns the length of the entire str1 string, and if the first character in str1 is not in str2, the function returns zero.

You can check the source string whether it contains the compared value of "size " or not.

reference.

Akina91
  • 322
  • 2
  • 5
  • 18