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():");
        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:");

    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");
    return 0;


>Solution :

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.

Leave a Reply