-1

我之前问过类似的问题,链接在这里。 C-将txt读入txt文件

刚刚发现给数组的第一列赋值为“size”的代码有一点问题。

我想在这里发布一个新的,希望任何人都可以提供帮助。


我在目录 /user/test/key.txt 中有一个 txt 文档。txt中的内容是这样的:

10 21 34 45 29 38 28
(blank line)
29 47 28 32 31 29 20 12 24
(blank line)

我想从 txt 中读取这些数字并写入一个两行数组。数组的长度可能会根据 txt 中较长的行而有所不同。并且在数组中可能会变成这样:

10 21 34 45 29 38 28 0 0
29 47 28 32 31 29 20 12 24

谢谢!

4

1 回答 1

1

嗯,这就是您明确接受的答案所做的,这是一个非常好的主意,因为您必须以某种方式确定特定行包含多少列。另一个方法是让每一行中的特殊值确定结尾(如'\0'字符串)。要拥有它,您可以按如下方式更改代码:

#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);
        // size+1 is still necessary, the additional element is now needed for the delimiting value instead of the number of elements
        key1[i] = malloc((size+1)*sizeof(int));
        /* CHANGE: don't store size in col 0
        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);
        }
        now we just do: */ 
        if(!key1[i]){
            fprintf(stderr, "It was not possible to secure the memory.\n");
            exit(2);
        }
        /* CHANGE: we start with index 0 */
        //for(int j = 1; j <= size ;++j){
        for(int j = 0; j < size ;++j){
            fscanf(fp, "%d", &key1[i][j]); 
        }
        /* CHANGE: we add a final value to determine the end of the row */
        key[i][size] = -1;   // choose a value that cannot occur in your data
    }
    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-22T16:50:59.270 回答