[英]Socket TCP/IP in C passing files and using Caesar cipher
我正在做一個項目,其中我需要通過 TCP 套接字傳遞文件,同時我必須使用 Caesar Cypher 加密文件的文本,但是我遇到了一個錯誤,就像您在上圖中看到的錯誤是“用數組類型分配表達式”,但我有幾個警告,我認為是由於我遇到的錯誤,你能幫我解決這個問題嗎?
我有完整的 int main 並且正在工作,因為我可以毫無問題地發送文件,但是我不能把整個代碼放在這里,因為我在創建問題時出錯了,所以 int main 是一個圖像
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#define BUF_SIZE 1024
void send_file(FILE *fp, int sockfd){
int n;
char data[BUF_SIZE] = {0};
while(fgets(data, BUF_SIZE, fp) != NULL) {
if (send(sockfd, data, sizeof(data), 0) == -1) {
perror("Error in sending file.");
exit(1);
}
bzero(data, BUF_SIZE);
}
}
void CaeserCypher(FILE *fp2, int key){
int i =0;
int cypherValue;
char cypher[BUF_SIZE]={0};
while(fgets(cypher, BUF_SIZE, fp2) != NULL){
cypherValue =((int)cypher[i]- 97 + key)%26 + 97;
cypher = cypherValue;
fprintf("%c", cypher);
i++;
}
bzero(cypher, BUF_SIZE);
}
int main(){
char *ip = "127.0.0.1";
int port = 9000;
int e;
int sockfd;
struct sockaddr_in server_addr;
FILE *fp, *fp2;
char *filename = "exemplo.txt";
int key=1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
perror("Error in socket");
exit(1);
}
printf("Server socket created successfully.\n");
server_addr.sin_family = AF_INET;
server_addr.sin_port = port;
server_addr.sin_addr.s_addr = inet_addr(ip);
e = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
if(e == -1) {
perror("Error in socket");
exit(1);
}
printf("Connected to Server.\n");
fp2 = fopen(filename, "w");
if (fp == NULL) {
perror("Error in reading file.");
exit(1);
}
void CaeserCypher(fp2, key);
fclose(fp2);
fp = fopen(filename, "r");
send_file(fp, sockfd);
printf("File data sent successfully.\n");
printf("Closing the connection.\n");
close(sockfd);
return 0;
}
當您聲明 cypher 時,您將其聲明為大小為 1024 的 char 數組。這與僅 char 不同。 您不能只為數組分配一個值(如 cypherValue)。 您需要使用索引將其分配給該數組的成員。 你可以用“cypher[index] = cypherValue;”之類的東西來做到這一點。
此外,fgets function 從文件中讀取一個字符數組並將它們放入傳遞給它的緩沖區(密碼)。 您當前 state 中的代碼在(嘗試)將其寫回文件之前只會加密該數組中的單個字符。
我說嘗試將其寫回文件的原因是因為您對 fprintf 的調用不起作用。 與 printf 不同,您需要在傳遞格式字符串之前傳遞 FILE* 作為第一個參數。 由於 cyppher 是一個字符數組,而不僅僅是一個字符,因此您需要使用 "%s" 作為格式字符串。
您可以在此處閱讀有關 fprintf function 的更多信息: https://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm
您的主要 function 也存在一些錯誤。 在第 65 行,您使用“w”以寫入模式打開 fp2。 這將刪除文件的內容,並且不會讓您讀取文件進行加密。 這是 fopen function 的參考: https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm
最后,第 66 行 fp 應該是 fp2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.