使用POPEN使用C编程将值存储到字符串

时间:2013-05-08 23:48:38

标签: c unix popen

我正在尝试在UNIX下编写C代码来读取文本每行的第三个单词,并使用POPEN将其存储到字符串中。但是我的代码在我的while循环内的行中给了我一个错误(赋值运算符需要可修改的左值)。这是我的代码:

    int main() {

int license = 0;
char number[100];


FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");
if ( file != NULL)
{
    char line [128];
    while (fgets(line, sizeof line, file) != NULL)
    {

        number = popen("cut -f3 -d' '", "r");

    }
    fclose (file);

    printf("Hello %s\n", number);
}

我知道这里有一些错误,因为我还是C的新手。但请帮我纠正,谢谢!

3 个答案:

答案 0 :(得分:1)

将popen的结果分配给固定大小的char数组。这是不可能的。

number = popen("cut -f3 -d' '", "r");

就像第一个popen一样 - >将其分配给FILE * file2

答案 1 :(得分:1)

FILE *file = popen("grep User results_today.TXT_05012013 > filename", "r");

这将运行grep命令查找User并将输出重定向到文件filename。它将返回一个FILE *,允许您读取此命令的输出,但由于该输出已被重定向,您将无法获得任何内容。

popen("cut -f3 -d' '", "r");

这将运行cut命令,因为它没有文件参数,将从stdin读取并写入stdout,这可以由popen返回的FILE *读取,但你不是无所事事。

你可能想要更像的东西:

char line[128];
int number;
FILE *file = popen("grep User results_today.TXT_05012013 | cut -f3 -d' '", "r");
if (file) {
    while (fgets(line, sizeof line, file)) {
        if (sscanf(line, "%d", &number) == 1) {
            printf("It's a number: %d\n", number);
        }
    }
    pclose(file);
}

答案 2 :(得分:0)

首先,我不是C程序员 这是我的实现(当然有许多借用线;))。 我只是厌倦了

popen
while fgets
 printf // I want to store in char* got it?

所以这是代码。它可能不完美,但做的工作:))

#include <stdio.h>
#include <stdlib.h>

#include <string.h>

char* concatenate(char * dest, char * source) {
    char * out = (char *)malloc(strlen(source) + strlen(dest) + 1);

    if (out != NULL) {
            strcat(out, dest);
            strcat(out, source);
    }

    return out;
}

char * executeCmd(char * cmd) {
    FILE *fp;

    int BUFF_SIZE = 1024;

    int size_line; 
    char line[BUFF_SIZE];

    char* results = (char*) malloc(BUFF_SIZE * sizeof(char));

    if (cmd != NULL) {
            /* Open the command for reading. */
            fp = popen(cmd, "r");
            if (fp != NULL) {

            /* Read the output a line at a time - output it. */
            while (fgets(line, size_line = sizeof(line), fp) != NULL) {
                    results = concatenate(results, line);
            }
            }
            /* close */
            pclose(fp);
    } // END if cmd ! null

    return results;
}


int main( int argc, char *argv[] ) {
    char * out = executeCmd("ls -l");
    printf("%s\n", out);

    return 0;
}