だから、テキストファイルを1行ずつ読み込んで、各行を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;
}