简体   繁体   中英

C - Write File Contents to a Buffer

I'm trying to open a file then send the contents to a TCP server. Currently, I am just opening the file and sending the data to a buffer, which will be accessed by the server. I am unsure of how to do this and also how to keep track of all the bits in a separate file. I'm not looking for a specific answer, just a step in the right direction will help loads! Thanks!

/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");

if (fp == NULL) {
    perror("Error opening the file");
    return(-1);
}

/* Send the contents of the input file to the server */ 
if (fgets(recvBuffer, buffer_size, fp)!=NULL) {

}

Simple example using your code:

/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");

/*create address struct*/
struct sockaddr_in dest;
bzero(&dest,sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr=inet_addr(/*addr*/); //ex "127.0.0.1"
dest.sin_port=htons(/*port*/); //ex 8888

if (fp == NULL) {
    perror("Error opening the file");
    return(-1);
}

int sock_fp = socket(AF_INET, SOCK_STREAM, 0); /*create socket with TCP transfer protocol*/
connect(sock_fp, (struct sockaddr *) &dest, sizeof(dest)); /*connect to server*/

/* Send the contents of the input file to the server */ 
while (fgets(recvBuffer, buffer_size, fp)!=NULL) {
    sendto(sock_fp, recvBuffer, strlen(recvBuffer), 0, (struct sockaddr *)&dest, sizeof(dest));
}

close(sock_fp);

Note that you need a server in the address that you provide listening on that port. Also note that I changed your if into a while loop in case the file contains more than 1 line (fgets reads by line)
Finally, as you can tell this contains minimal error checking, I would perform checks in case socket cannot create a socket or connect fails.

First you need to set up network infrastructure between client and server (try to find information about how to create simple client server app in C).

Then you can read the file in binary mode on the client side. Then you could decide if you want to send whole file to the server, or do so in chunks.

You need to account that network functions such as send/recv might send fewer bytes than you told them-so you might need to loop till you ensure all bytes are sent.

For a start, you might refer here , which addresses all main points I mentioned.

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