2know_clay
2016-09-28 13:33
采纳率: 100%
浏览 1.5k
已采纳

C语言中指针作为形参传递数据的问题

我想编写子函数readData读取文件中的数据,主函数中申请空间databuffer用于存储数据。
第一次调用子函数获取数据长度,然后申请空间,再次调用子函数将数据写入以申请的空间中。
但是调试总达不到效果。
代码如下:

 #include<stdio.h>
#include<malloc.h>
#define DATAFILE "test.bin"
  int readBuffer(char * fileName, float *data_buffer,int *data_num) {
    FILE *data_fp;
//  float *data_buffer;
    int data_size;
    int read_num = 0;
    int check = 1;
    if (*data_num == 0) {
        data_fp = fopen(fileName, "rb");
        if (data_fp == NULL) {
            printf("Open data file failed!\n");
            getchar();
            return -1;
        }
        fseek(data_fp, 0, SEEK_END);
        data_size = ftell(data_fp);
        *data_num = data_size / sizeof(float);
        fclose(data_fp);
        return 0;
    }
    while (check) {
        data_fp = fopen(fileName, "rb");
        if (data_fp == NULL) {
            printf("Open data file failed!\n");
            getchar();
            return -1;
        }
        fseek(data_fp, 0, SEEK_SET);
        data_size = *data_num * sizeof(float);
/*      fseek(data_fp, 0, SEEK_END);
        data_size = ftell(data_fp);
        fseek(data_fp, 0, SEEK_SET);
        data_buffer = (float*)malloc(data_size);*/
        *data_num = (int *) fread(data_buffer, sizeof(float), data_size/sizeof(float), data_fp);
        if (*data_num !=data_size/sizeof(float)) {
            printf("Read data failed!\nTry again now!\n");
            read_num++;
            fclose(data_fp);
        }
        else {
            check = 0;
            printf("Data read successed!\n");
        }

        if (read_num == 3) {
            check = 0;
            printf("we are read data file failed!\nPlease check the program!\n");
        }

    }
    if (read_num == 3) {
        getchar();
        return -1;
    }

    else
        return 0;
}

int main() {
    int error;
    char *fileName = "test.bin";
    float *data_buffer=NULL;
    int data_num=0;
    error = readBuffer(fileName,data_buffer,&data_num);
    if (error != 0) {
        printf("Get the number of data failed!\n");
        return -1;
    }
    data_buffer = (float*)malloc(data_num);
    error = readBuffer(fileName, data_buffer,&data_num);
    if (data_num==0) {
        printf("Read data failed!\n");
    }
    return 0;
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • devmiao 2016-09-28 16:05
    已采纳
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题