c - 在 C 中读写 pdf 或二进制数据

标签 c file-io

我正在实现 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

Corrupted file

最佳答案

由于二进制数据可以包含\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/

相关文章:

c - 如果我们改变 char* ptr = ; 指针指向的地址会改变吗?

c - 如何使用 ffmpeg 库从视频中提取灰度图像?

c - PPM 中显示的矩形中的 4 个三角形

multithreading - 本地写入文件与远程文件系统?

javascript - 如何使用CasperJS读取文件中的实时变化

ruby - 如何在 Ruby 中获取文件的天数?

vb.net - 正在读取文件的监视文件夹

c - 从键盘输入数据

c - 文件输出有两个换行符而不是一个

c++ - 如何在 Windows 上将 BYTE 数组映射为 FILE *