Find the answer to your Linux question:
Results 1 to 3 of 3
I want to write a program, that prints filenames, that might contain spaces, and use this output with other programs, e.g. Code: $ ls `myprogram` The filenames are saved as ...
  1. #1
    Just Joined!
    Join Date
    May 2008
    Posts
    7

    [C++] How to print filenames with spaces?

    I want to write a program, that prints filenames, that might contain spaces, and use this output with other programs, e.g.
    Code:
    $ ls `myprogram`
    The filenames are saved as const char* in my program, this example shows my problem:
    Code:
    #include <iostream>
    
    int main()
    {
      const char* file = "a b";
      std::cout << file << std::endl;
    }
    The ouput of this program is interpreted as the 2 files "a" and "b", but it actually should be the file "a b". How can i change that?

  2. #2
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    Quote Originally Posted by totycro View Post
    I want to write a program, that prints filenames, that might contain spaces, and use this output with other programs, e.g.
    Code:
    $ ls `myprogram`
    The filenames are saved as const char* in my program, this example shows my problem:
    Code:
    #include <iostream>
    
    int main()
    {
      const char* file = "a b";
      std::cout << file << std::endl;
    }
    The ouput of this program is interpreted as the 2 files "a" and "b", but it actually should be the file "a b". How can i change that?
    It depends on what are you exactly trying to do, but it shouldn't have anything to do with your program, but with the shell you are using. For example, in bash you must adequately quote everything.

    Code:
    ls -l "$(./myprogram)"
    Or:

    Code:
    for i in $(./myprogram); do ls -l "$i"; done

  3. #3
    Just Joined!
    Join Date
    May 2008
    Posts
    7
    I use zsh, but it should also work with bash.

    this just does the job if there's one file; the program however prints an arbitrary number of files and at least one
    Code:
    ls -l "$(./myprogram)"
    your second example got me thinking, it works if the files are separated with "\n":
    Code:
    ./myprogram | while read i ; do ls -l "$i"; done
    find handles this issue obviously the same way, so i guess it is the best possible way

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...