我在Linux2.4,C和使用gcc有一個奇怪的問題。Linux的貓:沒有這樣的文件或目錄
有一個小程序可以使用cat & grep cmd從文件中檢索信息。
#define tmpFile "/tmp/cli_tmp_file.txt"
#define MAX_CMD 50
void getRange()
{
char cmd[MAX_CMD+1];
// remove the temp file first
snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
system(cmd);
// create temp file
snprintf(cmd, MAX_CMD, "touch %s",tmpFile);
system(cmd);
// execute the command
snprintf(cmd, MAX_CMD, "echo \"Range:Max val 500\" > %s",tmpFile);
system(cmd);
// dump out the temp file so user could see
snprintf(cmd, MAX_CMD, "cat %s|grep \"Range\"", tmpFile);
system(cmd);
// remove the temp file
snprintf(cmd, MAX_CMD, "rm -f %s", tmpFile);
system(cmd);
}
當我執行這個代碼,我得到輸出 貓:/tmp/cli_tmp_file.txt:沒有這樣的文件或目錄
然而,在tmp文件夾中創建與內容
文件# pwd
/tmp
# ls -l
-rw-r--r-- 1 root root 68 Oct 10 12:54 cli_tmp_file.txt
#more /tmp/cli_tmp_file.txt
Range:Max val 500
同CMD的手動執行的,它顯示期望的輸出
# cat /tmp/cli_tmp_file.txt|grep Range
Range:Max val 500
任何幫助,將不勝感激。 在此先感謝。
您應該檢查'system'的返回值以查看命令是否成功。另外,嘗試在每個'snprintf'後面打印'cmd'緩衝區以查看它是否包含預期的命令。 –
刪除該文件,再試一次。 –
避免在'rm'中使用'system';考慮調用[remove(3)](http://man7.org/linux/man-pages/man3/remove.3.html)函數。要創建一個文件,只需「打開」文件,然後寫入文件「fclose」即可。不要忘記測試每個功能的失敗。 –