[英]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.