如何在 C++ 中将所有输入 (cin) 记录到文件中
事实上,我正在开发一个 minishell。我的函数可以工作,但是当我想将整个 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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您为每一行重新打开输出流outputFile,用每个新命令覆盖该文件。
编辑:正如其他海报所指出的,没有实际向输出文件写入内容可能是第二个原因。
You re-open the output stream outputFile for every line, overwriting the file with each new command.
Edit: As the other posters noted, not actually writing something to outputFile might be a second reason.
您打开
outputFile
,但从未向其中写入任何内容。那里应该出现什么?要将某些内容输出到文件中,请尝试
You open
outputFile
, but never write anything to it. What should appear there?To output something to the file, try
没有,
所以你没有写入文件
there are no
so you are not writing to the file
您的代码包含许多潜在的内存访问违规。
有一些库可以帮助您完成您想要做的事情(阅读和解释用户输入),例如 GNU Readline 库,它是用 C 编写的(但可以由 C++ 代码使用,就像所有 C 编写的库一样)。
有一些不错的 C++ 包装器,例如 SReadlineWrapper。
Your code contains a lot of potential memory access violations.
There are libraries to help you in what you are trying to do (reading and interpreting user input), for instance the GNU Readline library, which is coded in C (but can be used by C++ code, as is the case for all the C-written libraries).
There are some nice C++ wrappers, such as for instance SReadlineWrapper.