简体   繁体   中英

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;

}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM