【发布时间】:2015-03-01 11:34:02
【问题描述】:
我正在读取每行长度超过 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] = '\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]);
}
}
【问题讨论】:
-
您需要包含空字符:
for (x = 0; x < 21; x++) -
我应该把角色放在哪里。请原谅我是 C 的新手。谢谢@grc
-
按照@grc 的建议使用
for (x = 0; x < 21; x++) -
strncpy (a[0], line, 20); - 使用 \0 和 for 循环省去麻烦。
-
如果你只想要 63 个字符,为什么不让 fgets 来做呢?
fgets(a[i++], 63 , fp)
标签: c arrays string char truncate