【问题标题】:read and write from and into file从文件读取和写入文件
【发布时间】:2017-01-17 18:19:22
【问题描述】:

我正在尝试编写一个函数,该函数从用户那里获取数字并将它们放入文件中,然后读取它们并找到最小值。 这是我写的代码,但它根本不起作用。 有人可以帮我理解我做错了什么吗?我是 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;
}

【问题讨论】:

  • 运行程序后有没有看文件?
  • 你对while (!feof())的使用是wrong
  • @EOF 您在 SO 中拥有最合适的用户名来发布该评论。
  • @CPHPython 当我需要告诉某人不要将getchar() 的返回值存储到char 类型变量时,这一点很明显......
  • fgetc(fd) 返回unsigned char 范围内的值和EOF,一个负数。 min 将始终以 EOF 结尾。当fgetc() 返回EOF 时退出循环(或不进入循环)。也许还有其他问题。

标签: c file stdio


【解决方案1】:

这样修复

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多