I've been stuck on this for hours because I really don't understand file descriptors and how successfully print a file to one.

Basically, I want to be able to open a file and then echo its contents a character at a time to a socket file descriptor. The code below will hopefully help you to understand, and I've made a start on what I think is correct. I just can't figure out what to include in the while loop, although I think it is through use of char *fgets and int fputs. Any help whatsoever will be greatly appreciated.

void echoFile(int fd, char *filename) {

    // file pointer
    FILE* fp;
    
    // open 'filename' and assign the pointer
    if((fp = fopen(filename, "r")) == NULL) {
    	    fprintf(stderr, "The file specified does not exist\n");
    }
    
    //while loop to read each character from 'filename' to the file descriptor
    while(getc(fp) != EOF) {
  
    }
}

A file descriptor is conceptually much like the FILE pointer you use in standard C. In fact, on systems that use file descriptors (such as Linux and Unix) you'll find that the definition of the FILE struct actually stores one as a the underlying file handle.

On the assumption that you're using a compiler which supports fdopen(), that would be the easiest way to handle the file descriptor. What fdopen() does is create a FILE pointer from a file descriptor. Then you can use it just as you would fp:

void echoFile(int fd, char *filename) {
    FILE* out = fdopen(fd, "w");

    if (out != NULL) {
        FILE* fp = fopen(filename, "r");
        int ch;
 
        if(fp == NULL) {
            fprintf(stderr, "The file specified does not exist\n");
            return;
        }

        while ((ch = getc(fp)) != EOF) {
            putc(ch, out);
        }

        fclose(fp);
        fclose(out);
    }
}
This article has been dead for over six months. Start a new discussion instead.