How to create a new line using echo to write a file in C

hi ı am triying, to take the file data to a folder with a system function, this is the code

char path[100],command[120]; scanf("%s",&path); sprintf(command,"echo $(ls %s) > something.txt",path); system(command); 

but when I look at something.txt, there is no new line. This is the output, all on one line with many file names missing:

 acpi adjtime adobe apparmor.d arch-release asound.conf ati at-spi2 avahi bash.bash_logout ... wpa_supplicant X11 xdg xinetd.d xml yaourtrc 

I tried the -e -e -n echo options, but that didn't work. How to create a new line after each of these files?

+5
source share
2 answers

There is one new line to be expected. The echo command prints all its arguments on a single line, separated by spaces, which is the output you see.

You need to execute the result:

 echo "$(ls %s)" 

to keep newline characters in ls output. See Capturing multiline output to a Bash variable .

Using:

 snprintf(command, sizeof(command), "echo \"$(ls %s)\" > something.txt", path);` 

Of course, echo redundant; it would be better to just run:

 ls %s 

and therefore

 snprintf(command, sizeof(command), "ls %s > something.txt", path); 

If you save the echo, you should worry that the format string contains more than 20 additional characters, so 120 should be more than 130, if not 140.

You should also use scanf("%99s", path) (without ampersand; add a length limit) and ideally verify that it worked ( if (scanf(...) == 1) { ... OK ... } ).

+2
source

You cannot use echo . Do only

 sprintf(command,"ls %s > something.txt",path); system(command); 

When you use echo , it prints all the command line arguments to stdout, one by one, separated by a space character. The newline character (which is printed with the ls ) acts as an argument delimiter, as a space.

+6
source

All Articles