繁体   English   中英

如何在C ++中将所有输入(cin)记录到文件中

[英]How to log all input (cin) into file in C++

实际上,我正在研究一个小型的。 我的功能有效,但是当我想将整个cin东西(命令,参数,输出)记录到文件中时,文件中没有任何内容。 我无处可寻找带有参数的完整输入和输出的东西。

我希望有一个人可以帮助我。

我的代码:

using namespace std;

 ofstream outputFile;

void read_command(char *com, char **par){

    fprintf(stdout, "$");
    cin >> com;
    outputFile.open("logging.txt");     // file opened but nothing APPEARS IN IT????

        if(strcmp(com,"date")== 0){             // DATE
          time_t rawtime;
          time ( &rawtime );
          printf ( "%s", ctime (&rawtime) );
         }


        else if(strcmp(com,"echo")== 0)         // ECHO
        {
            string echo_part;
            cin >> echo_part;
            cout << echo_part << endl;

       }

        else if(strcmp(com,"sleep")== 0){           // SLEEP
            int howlong = 0;
            cin >> howlong;
            cout << "seconds: " << howlong << "....zZZzzZzz" << endl;
            sleep(howlong);

        }

        else if(strcmp(com,"ps")== 0)           // PROCESS
        {
            execlp("/bin/ps","ps","-A",NULL);       // ps  - command

        }

}

void handler(int p) {  // CTR-C handler

    cout << endl;
    cout << "Bye !" << endl;
    outputFile.close();
    alarm(1); // 2 seconds alarm ends process with kill
}


int main(){

    int childPid;
    int status;
    char command[20];
    char *parameters[60];
    signal(SIGINT,&handler); // CTR-C exit disabled



    while (1) {

      read_command(command, parameters);

        if ((childPid = fork()) == -1) {
            fprintf(stderr,"can't fork\n");
            exit(1);
        }
        else if (childPid == 0) { //child
            execv(command, parameters);
            exit(0);
        }
        else { // parent process
            wait(&status);
        }
    }
}

您为每一行重新打开输出流outputFile,用每个新命令覆盖该文件。

编辑:正如其他海报所指出的那样,实际上并没有向outputFile写一些东西可能是第二个原因。

你打开outputFile ,但从不写任何东西。 应该出现什么?

要输出文件,请尝试

outputFile << something

没有

outputFile << ...;

所以你没有写入文件

您的代码包含许多潜在的内存访问冲突。

有一些库可以帮助您完成您的工作(读取和解释用户输入),例如GNU Readline库 ,它用C编码(但可以被C ++代码使用,就像所有C的情况一样)写作的图书馆)。 有一些不错的C ++包装器,例如SReadlineWrapper

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM