所以我试图逐行阅读一个文本文件并将每行保存到一个char数组中。用strncpy将文件一行一行地拷贝到char数组中
从我在循环中的打印输出中,我可以告诉它正在计数行和每行正确的字符数,但我遇到了与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)? 您是否还可以重新格式化代码,使其显示为代码并更具可读性 - 例如,每条语句一行。 谢谢。 – ChrisBD 2010-07-13 15:46:47
我对代码进行了重新格式化,但for语句在各种编辑中以某种方式被肢解;请检查这是否是您正在使用的代码。 – 2010-07-13 15:52:33
我不确定你的问题的解决方案是什么,因为我有类似的问题,但我想我会给一个小建议:你应该能够使用strdup而不是自己mallocing内存,然后使用strncopy。 strdup将使用malloc来分配内存并处理复制过程。只为你节省一条线,但我是内置函数的忠实粉丝。 – Chris 2013-10-13 00:27:04