[英]When using the open command, and O_CREAT, it is appending a "?" to the end of the file name, how do I remove this?
所以我在C中使用open函數打開一個目標文件,如果它不存在,我會創建它。 我正在將標准輸出從終端重定向到這個文件。 當我運行我的程序時,它會使用我在 shell 中輸入的名稱創建一個新文件,但附加一個“?” 到最后。 有人可以幫我弄清楚如何刪除它嗎?
我的代碼在下面
// Take output from ls as input into the next argument.
command = strtok(NULL, " "); // Holds the value for the destination file.
printf("%s\n", command);
int targetFD = open(command, O_WRONLY | O_CREAT | O_TRUNC, 0700);
if (targetFD == -1)
{
perror("open()");
exit(1);
}
printf("The file descriptor for targetFD is %d\n", targetFD);
int result = dup2(targetFD, 1);
if (result == -1)
{
perror("dup2");
exit(2);
}
ls(); // instead of printing ls to the terminal, it gets written to the file.
這是示例執行的圖像。 注意junk.txt 文件是如何存在的...我希望我的程序將“ls”重定向到該文件或創建一個不存在的新文件。 示例程序執行
我打賭?
不是字面意思?
字符,但您的ls
版本顯示包含不可打印字符的文件名的方式,例如,如果您使用 GNU ls
並默認啟用-q
選項。
我還注意到,在您的示例輸出中, junk.txt
和The file descriptor for targetFD
之間有一個額外的空行。 您只在command
后打印了一個換行符,所以我懷疑字符串command
本身以\\n
結尾。 如果它是從以\\n
結尾的字符串(例如使用fgets
讀取的行)解析的,那將適合。 所以您實際上創建了一個名為junk.txt\\n
的文件,並且ls
將換行符打印為?
.
也許您想使用" \\n"
作為strtok
的分隔符字符串,這樣換行符也將被視為分隔符而不包含在標記字符串中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.