gpt4 book ai didi

c - 从文件中读取和写入

转载 作者:行者123 更新时间:2023-11-30 19:36:04 24 4
gpt4 key购买 nike

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

fclose(fd);
return min;
}

关于c - 从文件中读取和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41704264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com