| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
用freopen函数将stdin赋予了文件,用gets函数从stdin中读不到东西,但是用scanf读到了,就像gets函数啥也没干一样,这是为什么 
   
 
我的代码如下: 
 
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
 
#define LENGTH 81 
int main(void) { 
        FILE *pOut = NULL; 
        FILE *pIn = NULL; 
        char *filename = (char*)"myfile.txt"; 
        char mystr[100]={}; 
        char mystr_1[100] = {}; 
         
        if(NULL == (pOut = freopen(filename, "w+", stdout)) ) { 
                fprintf(stderr, "\nError assigning stdout to %s. Program terminated.", filename); 
                exit(1); 
        } 
        fprintf(stderr, "This output goes to %s.\n", filename); 
        printf("\nThis sentence should be writed to %s", filename);                         //把这句话写入文件 
        fclose(pOut); 
        pOut = NULL; 
         
        if(NULL == (pIn = freopen(filename, "r+", stdin)) ) { 
                fprintf(stderr, "\nError assigning stdin to %s. Program terminated.", filename); 
                exit(1); 
        }  
        gets(mystr_1);                                                                //从文件中读取字符串 
        scanf("%s", mystr);                                                        //再尝试从文件中读取字符串 
        fprintf(stderr, "\n%s%s", mystr_1, mystr); 
        fclose(pIn); 
        pIn = NULL; 
         
        return 0; 
}  
 
 
屏幕上的输出如下: 
This output goer to myfile.txt. 
 
This
- #include <stdio.h>
 
 - #include <stdlib.h>
 
 - #include <string.h>
 
  
- #define LENGTH 81
 
  
- int main(void) {
 
 -     FILE *pOut = NULL;
 
 -     FILE *pIn = NULL;
 
 -     //char *filename = (char *)"myfile.txt";
 
 -     const char *filename = "myfile.txt";
 
 -     //cchar mystr[100] = {};
 
 -     //char mystr_1[100] = {};
 
 -     if(NULL == (pOut = freopen(filename, "w+", stdout))) {
 
 -         fprintf(stderr, "\nError assigning stdout to %s. Program terminated.", filename);
 
 -         exit(1);
 
 -     }
 
 -     fprintf(stderr, "This output goes to %s.\n", filename);
 
 -     printf("\nThis sentence should be writed to %s", filename); //把这句话写入文件
 
 -     fclose(pOut);
 
 -     pOut = NULL;
 
 -     if(NULL == (pIn = freopen(filename, "r+", stdin))) {
 
 -         fprintf(stderr, "\nError assigning stdin to %s. Program terminated.", filename);
 
 -         exit(1);
 
 -     }
 
 -     //gets(mystr_1);      //从文件中读取字符串
 
 -     /*
 
 -     scanf("%s", mystr);   // 不是所有的系统都可以用gets函数,我这边就不能用
 
 -     scanf("%s", mystr_1); //再尝试从文件中读取字符串
 
 -     //fprintf(stderr, "\n%s%s", mystr_1, mystr);
 
 -     fprintf(stderr, "%s\n", mystr);
 
 -     fprintf(stderr, "%s\n", mystr_1);
 
 -     */
 
 -     int ch;
 
 -     while((ch = getchar()) != EOF) fputc(ch, stderr);
 
 -     fputc('\n', stderr);
 
 -     fclose(pIn);
 
 -     pIn = NULL;
 
 -     return 0;
 
 - }
 
 
  复制代码 
- $ ./main
 
 - This output goes to myfile.txt.
 
  
- This sentence should be writed to myfile.txt
 
  复制代码 
 
 
 |   
 
 
 
 |