How can I perfectly truncate a string in c?

2020-05-01 09:35发布

问题:

I am reading from a file of which each line is longer than 63 characters and I want the characters to be truncated at 63. However, it fails to truncate the lines read from the file.

In this program we are assuming that the file has 10 lines only:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char a[10][63];
    char line[255];

    int count = 0;

    //Open file                
    FILE *fp;
    fp = fopen("lines.dat", "r"); 

    //Read each line from file to the "line array"
    while(fgets(line, 255,fp) != NULL)
    {
        line[63] = '\0';

        //copy the lines into "a array" char by char
        int x;
        for(x = 0; x < 64; ++x)
        {
            a[count][x] = line[x];
        }

        count++;
    }

    fclose(fp);

    //Print all lines that have been copied to the "a array"
    int i;
    for(i = 0; i < 10; i++)
    {
        printf("%s", a[i]);
    }


}

回答1:

You have this result because you forgot to add the null string terminator in the end of a[0].

There's several ways to do it. My favorite one is to leave line as is: since it seems you want the truncated string elsewhere, you souldn't modify the source. In that case, you can replace:

//Tries to truncate "line" to 20 characters
line[20] = '\0';

//copying line to each character at a time
int x;
for(x = 0; x < 20; x++)
{
    a[0][x] = line[x];
}

with

//copying line to each character at a time
int x;
for(x = 0; x < 20; x++)
{
    a[0][x] = line[x];
}
a[0][20] = 0;


回答2:

i think you are missing the null byte.

You can get more info about this at : Null byte and arrays in C