目录"/user/doc“中有一个txt文档test.txt,如下所示:
10 21 34 45 29 38 28
29 47 28 32 31 29 20 12 24*用“空格”分隔的两行数字。
我想把数字写成2行数组,长度灵活。长度可能取决于txt文档一行中的更多数字的数量。在这个例子中,应该是9。
在此之后,数组看起来可能如下:
10 21 34 45 29 38 28 0 0
29 47 28 32 31 29 20 12 24第1行中的数字在数组中的第1行.第2行的数字在数组中的第2行。
下面的代码是一个接一个地填充数组,但我不知道如何修改它以满足我的需要。有人能帮忙吗?谢谢!
FILE *fp;
int key1[2][10];
if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL)
{
printf("\nCannot open file");
exit(1);
}
else
{
while(!feof(fp))
{
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 10 ;j++)
{
fscanf(fp, "%d", &key1[i][j]);
}
}
}
}
fclose(fp);发布于 2013-08-08 16:49:53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getColCount(FILE *fin){
long fpos = ftell(fin);
int count = 0;
char buff[BUFSIZ];
while(fgets(buff, sizeof(buff), fin)){
char *p;
for(p=strtok(buff, " \t\n");p;p=strtok(NULL, " \t\n"))
++count;
if(count)break;
}
fseek(fin, fpos, SEEK_SET);
return count;
}
int main(void){
FILE *fp;
int *key1[2];
if((fp = fopen("/Users/doc/test.txt", "rt")) == NULL){
printf("\nCannot open file");
exit(1);
}
for(int i = 0; i < 2; ++i){
int size = getColCount(fp);
key1[i] = malloc((size+1)*sizeof(int));
if(key1[i]){
key1[i][0] = size;//length store top of row
} else {
fprintf(stderr, "It was not possible to secure the memory.\n");
exit(2);
}
for(int j = 1; j <= size ;++j){
fscanf(fp, "%d", &key1[i][j]);
}
}
fclose(fp);
{//check print and dealocate
for(int i = 0; i < 2 ; ++i){
for(int j = 1; j <= key1[i][0]; ++j)
printf("%d ", key1[i][j]);
printf("\n");
free(key1[i]);
}
}
return 0;
}发布于 2013-08-08 16:02:07
用fgets逐行读取,然后用strtok拆分它们,用strtol解析它们。
就像这样:
char line[256];
int l = 0;
while (fgets(line, sizeof(line), input_file))
{
int n = 0;
for (char *ptr = strtok(line, " "); ptr != NULL; ptr = strtok(NULL, " "))
{
key1[l][n++] = strtol(ptr, NULL, 10);
}
l++;
}https://stackoverflow.com/questions/18130672
复制相似问题