Home > Blockchain >  Bad file descriptor fgets
Bad file descriptor fgets

Time:05-22

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;

}

CodePudding user response:

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.

CodePudding user response:

NOTE: This answer applies to revision 2 of the question. Meanwhile, OP has applied the fix recommended in this answer to the code in the question, thereby invalidating this answer.

You have closed fp, and then attempt to use it as if it were open when you pass it to send_file().

You either need to open another file and assign the pointer to fp, or leave fp open until after send_file() is completed.

  • Related