Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

There is one new line, which is 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 of:

echo "$(ls %s)"

to preserve the newlines in the ls output. See Capturing multiple-line output to a Bash variable.

Use:

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

Of course, the echo is redundant; it would be better simply to run:

ls %s

and hence:

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

If you keep the echo, you should worry about the fact that you have more than 20 extra characters in the format string so the 120 should be more like 130 if not 140.

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda