【发布时间】:2010-07-13 15:41:19
【问题描述】:
所以我试图逐行读取文本文件并将每一行保存到一个字符数组中。
从循环中的打印输出中,我可以看出它正在正确计算行数和每行的字符数,但我遇到了strncpy 的问题。当我尝试打印数据数组时,它只显示 2 个奇怪的字符。我从未与strncpy 合作过,所以我觉得我的问题可能与空终止有关。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
FILE *f = fopen("/home/tgarvin/yes", "rb");
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);
char *bytes = malloc(pos); fread(bytes, pos, 1, f);
int i = 0;
int counter = 0;
char* data[counter];
int length;
int len=strlen(data);
int start = 0;
int end = 0;
for(; i<pos; i++)
{
if(*(bytes+i)=='\n'){
end = i;
length=end-start;
data[counter]=(char*)malloc(sizeof(char)*(length)+1);
strncpy(data[counter], bytes+start, length);
printf("%d\n", counter);
printf("%d\n", length);
start=end+1;
counter=counter+1;
}
}
printf("%s\n", data);
return 0;
}
【问题讨论】:
-
你的文本文件是什么格式的?它是 ASCII 还是 Unicode(UTF-8 或 UTF-16)?您是否还可以重新格式化您的代码,使其显示为代码并且更具可读性 - 例如,每条语句一行。谢谢。
-
我重新格式化了代码,但是 for 语句在各种编辑中都被破坏了;请检查这是否真的是您正在使用的代码。
-
我不确定您的问题的解决方案是什么,因为我遇到了类似的问题,但是我想我会给出一个小提示:您应该能够使用 strdup 而不是 mallocing自己的内存,然后使用strncopy。 strdup 将使用 malloc 分配内存并处理复制过程。只会为您节省一行,但我是内置函数的忠实粉丝。
标签: c arrays null-terminated strncpy