[英]How to redirect standard output to a file — what's wrong with this code?
我在樹莓派pi2上使用C程序和433mhz接收器來讀取傳輸的代碼。 該程序嗅探433MHz的代碼。
要運行它,我使用以下命令: sudo ./RFSniffer
,如果找到了代碼,該程序將在控制台中顯示如下內容:
Received 5204
但是,我希望能夠在文件中獲取這些代碼,因此我嘗試了以下操作:
sudo ./RFSniffer >> codes.txt
但是沒有任何內容附加到我的codes.txt文件中……我也不知道為什么。 我的代碼有什么問題? 該文件始終為空。
這是我的代碼:
#include "RCSwitch.h"
#include <stdlib.h>
#include <stdio.h>
RCSwitch mySwitch;
int main(int argc, char *argv[]) {
int PIN = 2;
if(wiringPiSetup() == -1)
return 0;
mySwitch = RCSwitch();
mySwitch.enableReceive(PIN);
while(1) {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();
if (value == 0) {
printf("Unknown encoding");
} else {
printf("Received %i\n", mySwitch.getReceivedValue() );
}
mySwitch.resetAvailable();
}
}
exit(0);
}
問題可能是exit(0)
或printf()
而不是其他問題嗎?
編輯:
該程序是使用WiringPI lib編譯的,因此有一個標志“ -lwiringPi”
該工具在此處可用: https : //github.com/ninjablocks/433Utils/tree/master/RPi_utils
編輯2:
我將代碼更改為:
int main(int argc, char *argv[]) {
printf("yeah\n");
exit(0);
}
它僅適用於:
sudo sh -c './RFSniffer >> /home/pi/433Utils/RPi_utils/codes.txt'
因此,問題可能出while(1) { printf... }
嗎? 還是僅在調用exit(0)
時才寫入文件?
您正在使用默認緩沖的stdout進行編寫,並且由於我看不到循環中的任何break
, return
或exit
,因此我假設您使用Ctrl-C退出了程序。
並且所有緩沖到緩沖區中的值都將被簡單丟棄。 您應該在每次寫操作后僅清除stdout,以確保收到的內容將在您的文件中結束:
while(1) {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();
if (value == 0) {
printf("Unknown encoding");
} else {
printf("Received %i\n", mySwitch.getReceivedValue() );
}
fflush(stdout); // force immediate output
mySwitch.resetAvailable();
}
而且,無論如何,必須按Ctrl-C退出程序並不太好...
我相信您的問題是“ sudo”。 您確定知道codes.txt
在哪里嗎? 給它一個絕對路徑(例如>> /tmp/codes.txt
)。
沒有提供文件codes.txt
的寫許可權。
檢查ls -l codes.txt
並確認文件具有寫許可權。
文件的OR路徑不正確,因此請提供文件的絕對路徑:
sudo ./RFSniffer >> codes.txt
替換為
sudo sh -c `RFSniffer >> <absolute_path>/codes.txt`
OR
sudo ./RFSniffer | sudo tee <absolute_path>/codes.txt
該鏈接提供了有關使用sudo進行文件重定向的更多詳細信息: 如何使用sudo將輸出重定向到我沒有寫權限的位置?
我懷疑sudo
可能正在其他工作目錄下執行您的命令。 sudo pwd
打印什么? 您是否考慮codes.txt
在該目錄中查找codes.txt
?
編輯 :或者,可能是您的操作系統將stdout
臨時存儲在某個位置,直到程序關閉,此時程序將它寫入您的codes.txt
文件? 如果注入exit(0);
會發生什么? 在此代碼中每次調用printf
之后立即立即執行(或終止循環,無論如何...)
您可以使用tee命令 ,它將您的流數據存儲在文件中
您可以將其用作./RFSniffer | tee codes.txt
./RFSniffer | tee codes.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.