我正在实现 ftp
,我想上传和下载文件,当我下载或上传 pdf 文件时,它们已损坏。如何处理读取任何文件,使用 read()
和 write()
或 mmap
?下面是我尝试过的简化代码。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return (S_ISREG(path_stat.st_mode));
}
int ft_get_file_size(const char *filename)
{
struct stat file;
int fd;
if (!is_regular_file(filename))
return (-1);
fd = open(filename, O_RDONLY);
memset(&file, 0, sizeof(struct stat));
fstat(fd, &file);
close(fd);
return (file.st_size);
}
char *read_file(const char *filename)
{
char *content;
int file_size;
int fd;
ssize_t retval;
if ((file_size = ft_get_file_size(filename)) <= 0)
return (NULL);
content = (char *)malloc(sizeof(char) * file_size + 1);
fd = open(filename, O_RDONLY);
retval = read(fd, content, file_size);
content[retval + 1] = '\0';
close(fd);
return (content);
}
void write_file(char *file, char *content)
{
int fd;
fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd)
write(fd, content, strlen(content));
close(fd);
}
int main() {
char *test = read_file("ftp.en.pdf");
write_file("copy.pdf", test);
return EXIT_SUCCESS;
}
下载和上传文件的过程,是从文件中读取所有数据,然后将该数据发送到套接字。我已尝试使用 mmap
,但我仍然遇到损坏的文件。
Document is damaged error message
最佳答案
由于二进制数据可以包含\0
字符,您不能将您的内容视为字符串,因此strlen(content)
是错误的。您必须从 read_file
函数返回内容的大小。
例如,将您的函数定义为 char *read_file(const char *filename, int *size)
并在 *size
中返回大小。同样将您的写入函数定义为 void write_file(char *file, char *content, int size)
(忘记 malloc 中的 +1)
关于c - 在 C 中读写 pdf 或二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46365362/