Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bad file descriptor fgets

I’m trying to create a file to send information to another process. But when I reach the send_file function, I get –>Error in fgets():: Bad file descriptor. Can someone help me address this matter, please? I’m stuck.

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


void send_file(FILE *fp, int sockfd){
    char data[SIZE] = {0};
    
    if (fgets(data, SIZE, fp) == NULL){
        perror("\n -->Error in fgets():");
        }
    
    while (fgets(data, SIZE, fp) != NULL){
        if (send(sockfd, data, sizeof(data), 0) == -1){
            perror("\n -->Error in send():");
            exit(-1);
        } 
        bzero(data, SIZE);
    }
    
}

int main(int argc, char *argv[]){
    
    int clientfd, r;    
...
    char buffer[SIZE];
    
    clientfd = socket(AF_INET, SOCK_STREAM, 0);

...

    char *filenames = "file3.txt";
    FILE *fp = fopen(filenames, "w");
    
    if (fp == NULL){
        perror("\n -->Error creating file:");
        exit(-1);
    }
    

    char buff[30] = "This is a test text";
    fwrite(buff , 1 , sizeof(buff) , fp);
    
    
    printf("Contents: %s\n", (char *)fp);
    
    send_file(fp, clientfd);
    printf("Sent successfully.\n");
    fclose(fp);
    close(clientfd);
    
    return 0;

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

FILE *fp = fopen(filenames, "w");

Opens a file in write-only mode.

Use a read-write mode, such as "r+", "w+", or "a+", and fseek the file appropriately to the correct position after having placed whatever data you want in it.

See fopen for the semantics of each file access mode.

Alternatively, and arguably a better idea: close the file after writing to it, and reopen it in read-only mode.


The pattern of using fgets to initially check for EOF or error is flawed. If it succeeds, you will lose up to the first sizeof data - 1 bytes of information, as the buffer is unused before the next fgets call, which will either overwrite it or fail.


printf("Contents: %s\n", (char *)fp);

It is a wild assumption that casting a FILE * to a char * will somehow yield a string.

Don’t do this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading