Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make new line when using echo to write a file in C

hi ı am triying to take the data of files in a folder with 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 to the something.txt there is no new line. This is the output, all on one line with many file names omitted:

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 did try -e -E -n options of echo but it didn't work. How to make a new line after each of these files?

like image 698
Alper Fırat Kaya Avatar asked Jun 15 '15 21:06

Alper Fırat Kaya


People also ask

How do you skip a new line in echo?

The best way to remove the new line is to add '-n'. This signals not to add a new line. When you want to write more complicated commands or sort everything in a single line, you should use the '-n' option.

How do you add a new line at the end of a file in Unix?

For example, you can use the echo command to append the text to the end of the file as shown. Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.


1 Answers

You shouldn't use echo. Do just

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

When you use echo it outputs all command line arguments to the stdout, one by one, separated by the space character. Newline character (which is output of ls command) works as an argument separator, just as space.

like image 106
Oleg Andriyanov Avatar answered Sep 21 '22 06:09

Oleg Andriyanov