从文件读取和写入

时间:2017-01-17 18:19:23

标签: c file stdio

我试图编写一个从用户那里获取数字的函数,然后将它们放入文件然后读取它们并找到最小值。 这是我写的代码,但它根本不起作用。 有人可以帮我理解我做错了什么吗?我是C的新手。

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

int min_call(int, ...);


int main()
{
    int min;
    min = min_call(90,78,5,20,-1);
    printf("\n the minimum number is: %d ", min);

    min = min_call(70,40,2,-1);
    printf("\n the minimum number is: %d ", min);

    min = min_call(40,30,-1);
    printf("\n the minimum number is: %d ", min);

    return 0;
}


int min_call(int first, ...)
{
    int min;
    int currentNum;
    int i;
    va_list args;
    va_start(args,first);

    FILE *fd;

    if(!(fd=fopen("min_call_file.txt","a")))
    {
        fprintf(stderr, "cannot open file \n");
        exit (0);
    }

    for(i = first; i>=0; i=va_arg(args, int))
    {
        fprintf(fd, "%d", i);
    }
    va_end(args);

    fseek(fd,0,SEEK_SET);
    min = fgetc(fd);
    do
    {
        currentNum = fgetc(fd);
        if(currentNum < min)
            min = currentNum;


    }while(!feof(fd));

    fclose(fd);
    return min;
}

1 个答案:

答案 0 :(得分:0)

像这样修复

int min_call(int first, ...){
    int min;
    int currentNum;
    int i;
    va_list args;
    va_start(args,first);

    FILE *fd;

    if(!(fd=fopen("min_call_file.txt","w+"))){//w : new write each call, a : Straddle the call, + : To read later
        fprintf(stderr, "cannot open file \n");
        exit (0);
    }

    for(i = first; i>=0; i=va_arg(args, int)){
        fprintf(fd, "%d ", i);//put space after %d because Delimiter is required
    }
    va_end(args);

    fflush(fd);//Flush the buffer and to establish  the write
    fseek(fd, 0, SEEK_SET);
    fscanf(fd, "%d", &min);//read integer, not character
    do {
        if(1==fscanf(fd, "%d", &currentNum) && currentNum < min){
            min = currentNum;
        }
    }while(!feof(fd));

    fclose(fd);
    return min;
}