[英]How to find a string in a file and write a new string immediate next line of that search string in a file using C
[英]How to make new line when using echo to write a file in C
嗨我正在試圖獲取具有系統功能的文件夾中的文件數據這是代碼
char path[100],command[120];
scanf("%s",&path);
sprintf(command,"echo $(ls %s) > something.txt",path);
system(command);
但是當我查看something.txt時,沒有新行。 這是輸出,全部在一行上省略了許多文件名:
acpi adjtime adobe apparmor.d arch-release asound.conf ati at-spi2 avahi bash.bash_logout ... wpa_supplicant X11 xdg xinetd.d xml yaourtrc
我嘗試了-e
-E
-n
選項的回聲,但它沒有用。 如何在每個文件后創建一個新行?
你不應該使用echo
。 做吧
sprintf(command,"ls %s > something.txt",path);
system(command);
當您使用echo
它將所有命令行參數逐個輸出到stdout,由空格字符分隔。 換行符( ls
命令的輸出)用作參數分隔符,就像空格一樣。
有一條新線,這是預料之中的。 echo
命令將所有參數打印在由空格分隔的單行上,這是您看到的輸出。
您需要執行以下結果:
echo "$(ls %s)"
保留ls
輸出中的換行符。 請參閱捕獲多行輸出到Bash變量 。
使用:
snprintf(command, sizeof(command), "echo \"$(ls %s)\" > something.txt", path);`
當然, echo
是多余的; 運行起來會更好:
ls %s
因此:
snprintf(command, sizeof(command), "ls %s > something.txt", path);
如果你保持回聲,你應該擔心格式字符串中有超過20個額外字符的事實,所以如果不是140則120應該更像130。
您還應該使用scanf("%99s", path)
(沒有&符號;添加長度限制),理想情況下檢查它是否有效( if (scanf(...) == 1) { ... OK ... }
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.