我正在尝试编写一个函数,该函数从用户那里获取数字并将它们放入文件中,然后读取它们并找到最小值。这是我写的代码,但它根本不起作用。有人可以帮我了解我做错了什么吗?我是 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;
}
像这样修复
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", ¤tNum) && currentNum < min){
min = currentNum;
}
}while(!feof(fd));
fclose(fd);
return min;
}