0

popen を使用して「ls -la」コマンドの結果を取得し、その結果を C に書き込む C コードをいくつか書きました。コードは次のようになります。

unsigned int ls(char *destination, const char *username, const char *relative_path)
{
printf("LS IMP\n");
//if(!username || !relative_path) return -1; 
FILE *ls_pipe = NULL;
unsigned long ls_pipe_size = -1;

const char ls_command[] = "ls -la ";
char ls_path[255] = "/home/";   
char ls_full_command[255];

char buffer[255];
bzero(buffer, 255);

char *entries = NULL;   

bzero(ls_full_command, 255);

strcat(ls_path, username);
strcat(ls_path, relative_path);

strcat(ls_full_command, ls_command);
strcat(ls_full_command, ls_path);

printf("AFTER CATS\n");
ls_pipe = popen(ls_full_command, "r");

if(ls_pipe == NULL) return -1;

printf("Pipe ok!");

fseek(ls_pipe, 0, SEEK_END);
ls_pipe_size = ftell(ls_pipe);
rewind(ls_pipe);

printf("Filesize: %lu\n", ls_pipe_size);

int i;

for(i = 0; i < 100; i++)
{
    fread(buffer, 1, 255, ls_pipe);

    printf("%s", buffer);
}

//entries = (char*) malloc(sizeof(char) * ls_pipe_size);
//if(entries == NULL) return -1;
printf("Entries ok!\n");

//if(ls_pipe_size != fread(destination, sizeof(char), ls_pipe_size, ls_pipe))   return -1;

fclose(ls_pipe);
return strlen(destination);

}

問題は、パイプのサイズが巨大 (?) であり、適切な結果の後に 3 つのエントリが無限にノンストップで表示され始めることです。

wc -l で別の popen のようなものを使用して、結果の正確な行数を知らずにそれを読み取る方法はありますか?

ありがとう

PS 何が問題なのかをテストしようとしたときにコードにいくつかの変更があり、パイプの非常識なサイズのために malloc が機能しませんでした。

4

1 に答える 1