简体   繁体   中英

How to read string including escape characters in C using popen() in Linux?

I have to display all the files and sub-directories in a directory in Linux (more specifically, Ubuntu 19.10) using popen() in C. The relevant code is given below. The problem when I debug this code is, that, the "list" variable contains only up to the first "\\n" escape character, which is ".:\\n". How can I detour so that popen() outputs all the string including escape sequence characters?

#include <stdio.h>

int main()
{
    FILE *read_file;
    char list[1000];

    read_file = popen("ls -R","r");
    fgets(list, 1000, read_file);
    pclose(read_file);

    printf("%s", list);

    return(0);
}

@M Oehm. I tried like what you commented. But a segmentation fault arises as and when I try to do "fgets(list[++i], sizeof(char), read_file);".

#include <stdio.h>

int main()
{
    FILE *read_file;
    char list[1000];
    int i = -1;

    read_file = popen("ls -R","r");
    do
    {
        fgets(list[++i], sizeof(char), read_file);
    }while(list[i] != NULL);
    pclose(read_file);

    printf("%s", list);

    return(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM