如何在 C 中使用 printf 和 scanf 读写文件?

How to read and write files using printf and scanf in C?

一点背景故事:几年前,我参加了一个算法竞赛。那时我正在学习C,我不知道如何使用常规方法写入或读取文件。

为了不被新的方法和语法搞糊涂,一个 C 向导告诉我在 include 之后添加几行,然后 presto,任何使用 printf 打印到屏幕并从中获取输入的程序使用 scanf 的键盘将读取和写入这些行中声明的单独文件。

Windows中的那些代码只有运行,所以我不知道它是否可以移植。我不记得除了 stdio.h、conio.h 和 stdlib.h 之外还添加了 include。我在网上搜索了如何操作,但没有结果。有什么想法可以实现吗?

#include <stdio.h>
struct s
{
char name[50];
int height;
};
int main(){
    struct s a[5],b[5];   
    FILE *fptr;
    int i;
    fptr=fopen("file.txt","wb");
    for(i=0;i<5;++i)
    {
        fflush(stdin);
        printf("Enter name: ");
        gets(a[i].name);
        printf("Enter height: "); 
        scanf("%d",&a[i].height); 
    }
    fwrite(a,sizeof(a),1,fptr);
    fclose(fptr);
    fptr=fopen("file.txt","rb");
    fread(b,sizeof(b),1,fptr);
    for(i=0;i<5;++i)
    {
        printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
    }
    fclose(fptr);
}

你基本上有三个选择。


选项一

当您启动程序时,

重定向 stdin/stdout(这些是 scanf 读取和 printf 写入的流)。在 Windows 和 Linux 上,都可以这样做:

  • < in.txt - 将所有读取从 stdin 重定向到 in.txt
  • > out.txt - 将所有对 stdout 的写入重定向到 out.txt

你可以组合这些。例如,要让您的程序从 in.txt 读取并写入 out.txt,请在终端(命令行)中执行此操作:
myprogram < in.txt > out.txt


选项 2

同样,您可以重定向标准流,这次在您的代码中使用 freopen。例如:

freopen("out.txt", "w", stdout);
freopen("in.txt", "r", stdin);

结果将与上面完全相同。


选项 3

使用 C 的文件 I/O:首先 fopen,然后 fscanffprintf

FILE* fIn, fOut;
fIn = fopen("in.txt", "r");
fOut = fopen("out.txt", "w");
// Here you should check if any of them returned NULL and act accordingly

然后您可以像这样读写:

fscanf(fIn, "%d %d", &x, &y);
fprintf(fOut, "Some result: %d\n", result);