使用新表单从文件中读取和写入

时间:2017-02-01 23:49:45

标签: c file writing

我正在尝试从文件中读取,我必须使用它的新形式我不确定如何使用。我在下面发布了我必须使用的功能的图片,我不知道该怎么办这个错误以及如何修复它?求救!

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

double* read_file(FILE* file, int length);

int main(int argc, char* argv[])
{
    double* array = malloc(10 * sizeof(double));
    int length = atoi(*(argv + 1));
    FILE* file = *(argv + 2);

    if (argc < 4 || argc > 4)
    {
        printf("Insufficient arguments. Check your command line.\n");
        return 0;
    }

    array = read_file(file, length);
    printf("%p", array);
    return 0;
}

double* read_file (FILE* file, int length)
{
    FILE* ptr;
    double* array = malloc(length * sizeof(double));

    int i = 0;

    if ((ptr = fopen(file, "r")) == NULL)
    {
        return 0;
    }
    else
    {
        for (i = 0; i < length; i++)
        {
            fscanf(ptr, "%lf", (array + i));
        }
    }

    fclose(ptr);

    return array;
}

2 个答案:

答案 0 :(得分:0)

首先,您尝试将 char字符串分配给类型指向FILE 的指针的变量。编译器不允许你这样做。

// not allowed
FILE* file = *(argv + 2);

其次,您将指向FILE 的指针传递给fopen(),但是fopen()期望它的第一个参数是 char字符串所以这也行不通。

// file is FILE*, not allowed
ptr = fopen(file, "r"));

如果修复了这两行,代码应该编译。

答案 1 :(得分:0)

像这样修复

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

//double* read_file(FILE* file, int length);
//You do not need to pass a file pointer, you need a file name.
//It opens the file within this function
double *read_file(const char *filename, int length);

int main(int argc, char* argv[]){
    //if (argc < 4 || argc > 4)
    //argc < 4 || argc > 4 same as argc != 4
    //It is thought that it is 3 because only argv[1] and argv[2] are used.
    //It is necessary to check arguments before using them.
    if (argc != 3) {
        printf("Usage : %s number_of_elements file_name\n", argv[0]);
        printf("Insufficient arguments. Check your command line.\n");
        return 0;
    }

    //double* array = malloc(10 * sizeof(double));//It is not necessary as it is secured by read_file. Make memory leak.
    int length = atoi(argv[1]);
    const char *file = argv[2];

    double *array = read_file(file, length);
    if(array != NULL){
        for(int i = 0; i < length; ++i)
            printf("%f\n", array[i]);
        free(array);
    }
    return 0;
}

double* read_file (const char *file, int length){
    FILE *ptr;

    if ((ptr = fopen(file, "r")) == NULL){
        return NULL;
    }
    //It causes a memory leak unless you first confirm that the file can be opened
    double *array = malloc(length * sizeof(double));

    for (int i = 0; i < length; i++){
        if(1 != fscanf(ptr, "%lf", array + i)){
            printf("Failed to read the %ith element.\n", i+1);
            break;
        }
    }
    fclose(ptr);

    return array;
}