-3

我正在尝试使用指针数组从文件中读取两行。但是,我没有在屏幕上看到任何东西。我已经尝试在网上搜索,但无法解决问题。这是我在 mac 上使用 Netbeans 编写的代码。

int main(int argc, char** argv) {


            FILE *fp;
        char *points[50];
            char c;
        int i=0; 

        fp=fopen("/Users/shubhamsharma/Desktop/data.txt","r");
        if(fp==NULL)
        {
                printf("Reached here");
            fprintf(stderr," Could not open the File!");
            exit(1);
        }
            c=getc(fp);
        while(c!=EOF)
               {
                *points[i]=c;
                c=getc(fp);
                i++;
           } 

        for(int i=0;*points[i]!='\0';i++)
        {
                char d=*points[i];

            printf("%c",d);
                if(*(points[i+1])==',')
                {
                    i=i+1;
                }
        }
    return (EXIT_SUCCESS);
}
4

1 回答 1

1
char *points[50];

不是你想要的,这是一个包含 50 个指针的数组char

如果你想要一个指向你需要的指针数组char[50]

char (*points)[50];
points = malloc(sizeof(*points) * 2);

另请注意,fgets最好从文件中获取一行

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char (*points)[50];

    points = malloc(sizeof(*points) * 2);
    if (points == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    fgets(points[0], sizeof(*points), fp);
    fgets(points[1], sizeof(*points), fp);
    fclose(fp);
    printf("%s", points[0]);
    printf("%s", points[1]);
    free(points);
    return 0;
}
于 2015-09-24T08:12:41.120 回答