我怎样才能完美地截断c中的字符串?

How can I perfectly truncate a string in c?

我正在读取每行超过 63 个字符的文件,我希望字符在 63 处被截断。但是,它无法截断从文件中读取的行。

在这个程序中,我们假设文件只有 10 行:

#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] = '[=10=]';

        //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]);
    }


}

我认为您缺少空字节。

您可以在以下网址获得更多信息:Null byte and arrays in C

你有这个结果是因为你忘记在 a[0] 的末尾添加空字符串终止符。

有几种方法可以做到这一点。我最喜欢的是保持原样:因为您似乎希望在其他地方使用截断的字符串,所以您不必修改源代码。 在这种情况下,您可以替换:

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

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

//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;