使用fread()从文件中读取时,缓冲区中的空间比预期的要多。因此,如果原始文档为22个字符,则file_size
和result
将为22个字符,而text
将为30个字符。
对我来说这没有意义,并且已经尝试了一段时间。关于为什么发生这种情况以及解决方案的任何想法?我是C的新手。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* For Windows machines */
#if defined(_WIN32) || defined(_WIN64)
#define PLATFORM_NAME "windows"
#define CWD_PLATFORM (cwd = _getcwd(NULL, 0)
#include <direct.h>
#endif
/* For Linux machines */
#if defined(__linux__)
#define PLATFORM_NAME "linux"
#define CWD_PATH_MAX PATH_MAX
#define CWD_PLATFORM (cwd = getcwd(NULL, 0)
#include <unistd.h>
#endif
#include <limits.h>
#include "encrypt_text.h"
#define MAX_FILE_SIZE 512
void read_from_file(void);
void read_from_file(void) {
char file_name[MAX_FILE_SIZE];
char *cwd;
char *text;
FILE *file;
long file_size;
size_t result;
/* Getting the name of the file to be encrypted */
printf("Enter the name of the file to be encrypted: ");
fgets(file_name, MAX_FILE_SIZE, stdin);
file_name[strcspn(file_name, "\n")] = 0;
/* Checking if there are any errors in opening */
if((file = fopen(file_name, "r")) == NULL) {
perror("Cannot open file");
exit(EXIT_FAILURE);
}
/* Getting the file size */
fseek(file, 0, SEEK_END);
file_size = ftell(file);
rewind(file);
/* Allocating memory based on the file size */
text = (char *) malloc(sizeof(char) * file_size);
if(text == NULL) {
perror("Insufficient memory");
exit(EXIT_FAILURE);
}
printf("file_size:: %d\n", file_size); //debug
/* Copying the file into the text buffer */
result = fread(text, sizeof(char), file_size, file);
if(result != file_size) {
perror("Error reading file");
exit(EXIT_FAILURE);
}
printf("RESULT:: %d\n", result);
printf("file_size:: %d\n", file_size); //debug
printf("TEXT STRLEN:: %d\n", strlen(text)); //debug
/* Creating a new file with the ".enc" extension */
char *cipher_text = encrypt_text(text);
char *new_file = strcat(file_name, ".enc");
/* Creating the file in write mode */
file = fopen(new_file, "w");
/* Writing to the new file */
fwrite(cipher_text, sizeof(char), strlen(cipher_text), file);
/* Closing the file stream */
fclose(file);
/* Getting the Current Working Directory (CWD) */
if(CWD_PLATFORM) != NULL) {
if(PLATFORM_NAME == "windows") {
printf("Saved encrypted text to: %s\\%s\n", cwd, new_file);
}
else if(PLATFORM_NAME == "linux") {
printf("Saved encrypted text to: %s/%s\n", cwd, new_file);
}
} else {
perror("CWD error");
exit(EXIT_FAILURE);
}
/* Deallocating allocated memory */
free(text);
}