簡體   English   中英

C-將文件內容寫入緩沖區

[英]C - Write File Contents to a Buffer

我正在嘗試打開文件,然后將內容發送到TCP服務器。 當前,我只是打開文件並將數據發送到緩沖區,服務器將訪問該緩沖區。 我不確定如何執行此操作以及如何跟蹤單獨文件中的所有位。 我不是在尋找特定的答案,只是朝正確方向邁出的一步將有助於您加載! 謝謝!

/* 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) {

}

使用代碼的簡單示例:

/* 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);

請注意,您需要在該端口上提供監聽地址的服務器。 另請注意,如果文件包含多於1行(fget按行讀取),我將if更改為while循環
最后,正如您所知,它包含最少的錯誤檢查,如果socket無法創建套接字或connect失敗,我將執行檢查。

首先,您需要在客戶端和服務器之間建立網絡基礎結構(嘗試查找有關如何在C中創建簡單的客戶端服務器應用程序的信息)。

然后,您可以在客戶端以二進制模式讀取文件。 然后,您可以決定是要將整個文件發送到服務器,還是分塊發送。

您需要考慮到諸如send/recv類的網絡功能可能發送的字節數少於您告訴他們的字節數-因此,您可能需要循環直到確保所有字節都已發送。

首先,您可以在這里參考,它解決了我提到的所有要點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM