为什么我不能阅读输入的文本文件?

问题描述 投票:0回答:1

我尝试使用scanf读取文件名,但失败。我的指针非常糟糕,找不到问题。指向字符串数组的指针有问题吗?这是我的代码:

int* Read_file(char* str[])
{
    FILE* fp = fopen(str[1], "r");
    if(fp == NULL)
    {
        printf("File cannot open\n");
        return NULL;
    }
    int rows = 0;
    while(!feof(fp))
    {
        if(fgetc(fp) == '\n')
        {
            rows ++;
        }
    }
    rows ++;
    int* keys = (int*)malloc(3 * rows * sizeof(int));
    fseek(fp, 0L, 0);
    while(!feof(fp))
    {
        for(int i = 0;i < rows;i ++)
        {
            for(int j = 0;j < 3;j ++)
            {
                fscanf(fp,"%d", &keys[(3 * i) + j]);
            }
        }
    }
    fclose(fp);
    return keys;
}
int main()
{
    char* str[20];
    printf("Build_tree ");
    scanf("%s",&str);
    int* keys = Read_file(str);
    return 0;
}
string file pointers scanf fopen
1个回答
0
投票

我认为您的代码应该像

int* Read_file(char* str[])
{
    FILE* fp = fopen(str, "r");
    if(fp == NULL)
    {
        printf("File cannot open\n");
        return NULL;
    }
    int rows = 0;
    while(!feof(fp))
    {
        if(fgetc(fp) == '\n')
        {
            rows ++;
        }
    }
    rows ++;
    int* keys = (int*)malloc(3 * rows * sizeof(int));
    fseek(fp, 0L, 0);
    while(!feof(fp))
    {
        for(int i = 0;i < rows;i ++)
        {
            for(int j = 0;j < 3;j ++)
            {
                fscanf(fp,"%d", &keys[(3 * i) + j]);
            }
        }
    }
    fclose(fp);
    return keys;
}
int main()
{
    char str[20];
    printf("Build_tree ");
    scanf("%s",str);
    int* keys = Read_file(str);

    //Whatever you want to do with the keys

    return 0;
}

对任何查询的评论。

© www.soinside.com 2019 - 2024. All rights reserved.