Search code examples
cstdinfgetsstrncpy

Strange strncpy, fgets behaviour


I'm basically writing the code to reading things that store the rest of the string if it starts with an l. Here is my code so far:

char input[80];
char fileName[80];

fgets(input, 80, stdin);   //Need to use because only want to read maximum 80 characters

if(input[0] == 'l') {
    printf("String length: %d\n", strlen(input));
    printf("String input: %s", input);
    strncpy(fileName, &input[1], (strlen(input)) -2);
    fileName[strlen(input)-1] = '\0';
    printf("Filename to save: %s \n", fileName);
}

When I input ljudyjudyjudyjudy the filename I get when I printf is judyjudyjudyjudyH

It works sometimes with different inputs, but sometimes extra characters prop up?


Solution

  • I think you are off by one:

    fgets(input, 80, stdin);   //Need to use because only want to read maximum 80 characters
    
    if(input[0] == 'l') {
        printf("String length: %d\n", strlen(input));
        printf("String input: %s", input);
        strncpy(fileName, &input[1], (strlen(input)) -2);
        fileName[strlen(input)-2] = '\0'; // should be -2 instead
        printf("Filename to save: %s \n", fileName);
    }
    

    In your example with "ljudyjudyjudyjudy" as input, you want to set fileName[16] to '\0' rather than fileName[17].