Search code examples
cstringprintfstdin

How to retrieve a portion of a string?


I'm reading in a string of file permissions from stdin and I want to create another string that will hold all characters expect the first from the string the user inputs in stdin.

int main(){
  char allPermissions[10];
  char permissions[9];

  scanf("%s", allPermissions);


  for(int i = 1; i <= 9; i++) {
    char temp = allPermissions[i];
    //printf("%c", temp);
    permissions[i-1] = temp;
  }
  printf("%s\n", permissions);

  return 0;
}

If the user inputs: drwx------

Then I expect the program to output: rwx------

But what I get is: rwx------drwx-------

And I'm not entirely sure why.


Solution

  • Looping through the entire string and copying each element one by one into the destination string works, but it is inefficient and unidiomatic C. You can accomplish this in O(1); after reading the string from stdin, just point one after the start of the string:

    printf("%s\n", allPermissions + 1);
    

    This will also work for operations such as copying the string to a new buffer:

    strcpy(permissions, allPermissions + 1);
    

    Do note that an array size of 10 is insufficient for reading a string like 'drwx------' since you also need to take the null terminator into account. In general, I wouldn't use scanf-family functions to read from stdin; fgets is a better choice.