简体   繁体   English

如何使用C(linux)中的管道将GCC的输出保存在文件中?

[英]how to save the output of GCC in a file using pipes in C (linux)?

on execution, file creation is working well...but nothing gets written into it...what could be done...is there any other way apart from using file descriptors..?? 在执行时,文件创建运行良好......但没有任何内容写入...可以做什么......除了使用文件描述符之外还有其他方法吗?

I tried the following code: 我尝试了以下代码:

    memset(buffer, '\0', sizeof(buffer));
    read_fp = popen("gcc test1.c", "r");
    //fp = fopen("/home/pranav/Desktop/b4.txt","w");
    fd = open("beejoutput2.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP  |         S_IROTH);
    if (read_fp != NULL)
    {

        chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp);
        while (chars_read > 0)
        {

    /*writing to the file*/
        while ((bytesread = read(3, buffer, chars_read)) > 0) 
                write(fd, buffer, bytesread);

        buffer[chars_read-1] = '\0';
        printf("Reading %d:-\n %s\n", BUFSIZ, buffer);
        //fprintf(fp,"%d:-\n %s\n", BUFSIZ, buffer);
        chars_read = fread(buffer, sizeof(char), BUFSIZ, read_fp);
        }



    pclose(read_fp);
    exit(EXIT_SUCCESS);
    }
    //fclose(fp);
    exit(EXIT_FAILURE);
    return 0;
    }

Error messages will be on stderr, so change this 错误消息将在stderr上,因此请更改此设置

read_fp = popen("gcc test1.c", "r"); read_fp = popen(“gcc test1.c”,“r”);

to this 对此

read_fp = popen("gcc test1.c 2>&1", "r"); read_fp = popen(“gcc test1.c 2>&1”,“r”);

  1. You should test the output of open and write since they fail. 你应该测试openwrite的输出,因为它们失败了。
  2. You should not use system calls like open and write directly, they have portable C wrappers like fopen and fwrite . 你不应该使用像openwrite这样的系统调用,它们有像fopenfwrite这样的可移植的C包装器。
  3. Close all the things at the end. 最后关闭所有的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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