06月07, 2013

如何在C/C++中方便地读写文件

注意:这是一篇从旧博客恢复的文章。

原地址:http://freemeepo.com/acm/786.html


C语言中,有一系列读写文件的函数,是从控制台输入输出函数增加一个文件指针参数改过来的,例如scanf、printf、puts改成了fscanf、fprintf、fputs,但是这样未免太麻烦了。有没有方法可以做到:依然用那些控制台输入输出函数,达到读写文件的效果呢?

方法1:

使用freopen函数。这个函数可以将控制台输入输出(stdin、stdout)当做文件进行输入输出。以下为模板。

  • #include <stdio.h>
  • int main()
  • {
  • freopen("in.txt","r",stdin);
  • freopen("out.txt","w",stdout);
  • /* 代码内容 */
  • fclose(stdin);
  • fclose(stdout);
  • return 0;
  • }
cpp

方法2:

用CMD带参数执行exe。(编译成main.exe)示例:

  • main <in.txt >out.txt

意为读入in.txt,输出到out.txt。

本文链接:https://debug.fanzheng.org/post/how-to-read-and-write-files-conveniently-in-C-and-CPP.html

-- EOF --

Comments

Comments
  • Latest
  • Oldest
  • Hottest
Powered by Waline v3.5.7