0

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;
    }
artless noise
  • 21,212
  • 6
  • 68
  • 105
  • 1
    First, your output might be on stderr rather than stdout. Next, your code is a bit of a puzzle. You appear to do an initial (huge) fread but then discard that output. Then you inexplicable read from hard coded file descriptor 3??? And then you fread some more, again discarding the result... – Chris Stratton Apr 30 '14 at 19:31
  • Why the `(bytesread = read(3, buffer, chars_read)`, why do you hardcode the file descriptor 3? – Basile Starynkevitch Apr 30 '14 at 20:04
  • Read [Advanced Linux Programming](http://advancedlinuxprogramming.com/) since your code is very confused! You may want to code an event loop, see [this](http://stackoverflow.com/a/20582916/841108) .... – Basile Starynkevitch Apr 30 '14 at 20:05

2 Answers2

1

Error messages will be on stderr, so change this

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

to this

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

Soren
  • 14,402
  • 4
  • 41
  • 67
1
  1. You should test the output of open and write since they fail.
  2. You should not use system calls like open and write directly, they have portable C wrappers like fopen and fwrite.
  3. Close all the things at the end.
Grapsus
  • 2,714
  • 15
  • 14