Chinaunix首页 | 论坛 | 博客
  • 博客访问: 483522
  • 博文数量: 118
  • 博客积分: 5003
  • 博客等级: 大校
  • 技术积分: 1213
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-07 20:29
文章存档

2011年(8)

2010年(4)

2009年(12)

2008年(85)

2007年(9)

我的朋友

分类: LINUX

2008-10-22 16:49:55

解答: 为了暂时重定向标准的输出输出(如 printfscanf 函数实现输入输出)到一个文件,你需要改变stdinstdout 文件指针。下面两个例子显示具体实现方法:

例1:

这个例子把行信息打印到stdio窗口,然后再有一行到文件,接着又有一行到stdio屏幕。

#include
int main (int argc, char *argv[])
{
FILE *copy;

printf ("This is printed to screen!\n");
copy = stdout;
stdout = fopen ("stdio test.txt", "w");
printf ("This is printed to a file!\n");
fclose (stdout);
stdout = copy;
printf ("Where is this line?\n");
return 0;
}



例2:

这个例子从屏幕读取一个数,然后从文件中读取第一个单词(从第一个空格算起),然后又从控制台读取一个字符串。

#include
int main (int argc, char *argv[])
{
FILE *copy;
int x;
char y[100] = "\0";

printf ("This is printed to screen!\n");
scanf ("%d", &x);
copy = stdin;
stdin = fopen ("stdio test.txt", "r");
scanf ("%s", y);
fclose (stdin);
stdin = copy;
printf ("%s\n", y);
scanf ("%s", y);
printf ("%s\n", y);
return 0;
}
阅读(2249) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~