[英]Redirecting output to a file in linux
我正在编写一个ac程序,该程序设置Raspberry PI(Debian Wheezy)和调制解调器之间的串行通信。 该程序到目前为止工作正常,但我希望输出也可以在.txt或.csv文件中重定向。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#define MODEM "/dev/ttyUSB0"
#define BAUDRATE B9600
int main(int argc,char** argv)
{
struct termios tio;
struct termios stdio;
struct termios old_stdio;
int tty_fd, flags;
unsigned char c='D';
tcgetattr(STDOUT_FILENO,&old_stdio);
printf("Starte bitte %s /dev/ttyUSB0\n",argv[0]);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
if((tty_fd = open(MODEM , O_RDWR | O_NONBLOCK)) == -1){
printf("Error while opening\n"); // Just if you want user interface error control
return -1;
}
cfsetospeed(&tio,BAUDRATE);
cfsetispeed(&tio,BAUDRATE); // baudrate is declarated above
tcsetattr(tty_fd,TCSANOW,&tio);
while (c!='q'){
if (read(tty_fd,&c,1)>0){
write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
printf("");
}
if (read(STDIN_FILENO,&c,1)>0){
write(tty_fd,&c,1);//if new data is available on the console, send it to serial port
printf("");
}
}
close(tty_fd);
tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
return EXIT_SUCCESS;
}
希望有人可以帮助我
为什么不在程序之外执行该操作?
下面将把程序的(std)输出写入文件foo.txt
:
./myprogram > foo.txt
如果您还想查看输出,请将其通过tee
管道传输(它将把stdin写入stdout 和一个文件)
./myprogram | tee foo.txt
如果您完全确定要在程序中执行所有这些操作,则可能需要编写自己的write
函数,该函数既可以写到stdout
,也可以写到文件。
ssize_t mywrite(int fd, const void *buf, size_t count) {
write(fd, buf, count);
return write(STDOUT_FILENO, buf, count);
}
然后用它,而不是write
(请注意,你应该通过一个打开的文件的文件描述符,以mywrite
;它也将写入stdout)
目前尚不清楚为什么您不简单地open()
新路径并对其进行write()
而不是写入stdout。 如果这不是一个选择(在您的示例代码中,这似乎是一个选择,最好的选择),则可以使用此伪代码执行运行时重定向。
#include <unistd.h>
// first open the new output path
int new_out = open("/path/to/output", flags_as_needed);
// next, move the standard output path
int save_out = dup(STDOUT_FILENO);
close(STDOUT_FILENO);
// now copy the new output path to the standard output position
dup2(STDOUT_FILENO, new_out);
只需打开一个文件并使用其文件描述符即可:
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main()
{
char block[1024]; //buffer of data
int out; //file deccriptor
int nread; //size of data
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
write(out,block,nread);
exit(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.