首页 文章

动态读取文本文件并放入C中的指针char数组

提问于
浏览
0
int i=0;
int numProgs=0;
char* input[500];
char line[500];
FILE *file;
file = fopen(argv[1], "r");
while(fgets(line, sizeof line, file)!=NULL) {
    /*check to be sure reading correctly
    add each filename into array of input*/
    input[i] = (char*)malloc(strlen(line)+1);
    strcpy(input[i],line);
    printf("%s",input[i]);/*it gives the hole line with\n*/
    i++;
    /*count number of input in file*/
    numProgs++;
}
/*check to be sure going into array correctly*/
fclose(file);

我不知道每行的输入txt的大小,所以我需要动态地做 . 我需要使用char * input []这种类型的数组,我还需要使用int numProgs保存行号 . 输入文本文件有多行,每行都有未知的字符大小 .

1 回答

  • 0
    FILE *file;
    file = fopen("test.txt", "r");
    fseek(file, 0, SEEK_SET);
    int numRow = 1, c;
    while ((c = fgetc(file)) != EOF)
    {
        if (c == '\n')
            numRow++;
    }
    fseek(file, 0, SEEK_SET);
    char **input;
    input = malloc(sizeof(char) * numRow);
    int i, j = 0, numCol = 1, curPos;
    for (i = 0; i < numRow; i++)
    {
        curPos = (int)ftell(file);
        while((c = fgetc(file)) != '\n')
        {
            numCol++;
        }
        input[i] = malloc(sizeof(char) * numCol);
        fseek(file, curPos, SEEK_SET);
        while((c = fgetc(file)) != '\n')
        {
            input[i][j++] = c;
        }
        input[i][j + 1] = '\n';
        numCol = 1;
        j = 0;
    }
    

相关问题