仍在与C的小提琴阶段。不知道我在这里做错了什么,但我认为它与指针有关。无论如何。我正在尝试读入并将制表符分隔的文本文件解析为2D数组。实际的数组是6109 x 14,我分配了一个更大的指针数组。
FILE *in = fopen("afile","rt");
// read the first line from the file
char line[2000];
int x=0;
int y=0;
char *result[7000][14];
char *curResult;
char delim[]= "\t";
while (fgets(line, 2000, in) != NULL) {
printf("LINE IS %s\n",line);
curResult=NULL;
curResult = strtok(line,delim);
y=0;
while( curResult != NULL ) {
result[x][y]= curResult;
curResult = strtok( NULL, delim );
y++;
}
x++;
}
//print a random line to check
for(int i=0; i<10; i++)
printf("%s\n", result[50][i]);
我在底部打印的行应该是第50行,打印文本文件的最后一行。我用不同的数字而不是50来尝试这个,但它们都打印相同的东西。
编辑:afile看起来像这样:
instance_id batch_id cmap_name INN1 concentration (M) duration (h) cell2 array3 perturbation_scan_id vehicle_scan_id4 scanner vehicle vendor catalog_number catalog_name
1 1 metformin INN 0.00001 6 MCF7 HG-U133A EC2003090503AA EC2003090502AA HP GeneArray Scanner medium Sigma-Aldrich D5035 "1,1-dimethylbiguanide hydrochloride"
2 1 metformin INN 0.00001 6 MCF7 HG-U133A EC2003090504AA EC2003090502AA HP GeneArray Scanner medium Sigma-Aldrich D5035 "1,1-dimethylbiguanide hydrochloride"
3 1 metformin INN 0.0000001 6 MCF7 HG-U133A EC2003090505AA EC2003090502AA HP GeneArray Scanner medium Sigma-Aldrich D5035 "1,1-dimethylbiguanide hydrochloride"
4 1 metformin INN 0.001 6 MCF7 HG-U133A EC2003090506AA EC2003090502AA HP GeneArray Scanner medium Sigma-Aldrich D5035 "1,1-dimethylbiguanide hydrochloride"
21 2 phenformin INN 0.00001 6 MCF7 HG-U133A EC2003091104AA EC2003091102AA HP GeneArray Scanner medium Sigma-Aldrich P7045 phenformin hydrochloride
22 2 phenyl biguanide 0.00001 6 MCF7 HG-U133A EC2003091105AA EC2003091102AA HP GeneArray Scanner medium Sigma-Aldrich P19906 1-phenylbiguanide hydrochloride
23 2 valproic acid INN 0.001 6 MCF7 HG-U133A EC2003091106AA EC2003091102AA HP GeneArray Scanner medium Sigma-Aldrich P4543 2-propylpentanoic acid
61 2a metformin INN 0.00001 6 MCF7 HG-U133A EC2003091103AA EC2003091102AA HP GeneArray Scanner medium Sigma-Aldrich D5035 "1,1-dimethylbiguanide hydrochloride"
答案 0 :(得分:1)
想象一下,line
是一个大盒子,你可以放一堆字母
这就是你对fgets()
所做的。
接下来,您指向该框内的特定字母。
接下来,您将框的内容(另一个fgets()
)替换为相同的变量line
),指针当然仍然指向同一个框,但现在指向新的字母。
您需要在循环内的某处复制字符(strcpy()
,检查您是否有足够的空间。)