温馨提示×

C语言怎么实现文件的上传与下载

小亿
121
2023-12-13 16:50:30
栏目: 编程语言

在C语言中,可以使用标准库中的文件指针来实现文件的上传与下载操作。以下是一个简单的示例代码:

文件上传:

#include <stdio.h>

int main() {
    FILE *sourceFile, *destFile;
    int ch;

    // 打开要上传的文件
    sourceFile = fopen("source.txt", "rb");
    if (sourceFile == NULL) {
        printf("无法打开要上传的文件!\n");
        return 1;
    }

    // 创建目标文件
    destFile = fopen("destination.txt", "wb");
    if (destFile == NULL) {
        printf("无法创建目标文件!\n");
        fclose(sourceFile);
        return 1;
    }

    // 逐个字节地将源文件内容写入目标文件
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destFile);
    }

    printf("文件上传成功!\n");

    // 关闭文件
    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

文件下载:

#include <stdio.h>

int main() {
    FILE *sourceFile, *destFile;
    int ch;

    // 打开要下载的文件
    sourceFile = fopen("source.txt", "rb");
    if (sourceFile == NULL) {
        printf("无法打开要下载的文件!\n");
        return 1;
    }

    // 创建目标文件
    destFile = fopen("destination.txt", "wb");
    if (destFile == NULL) {
        printf("无法创建目标文件!\n");
        fclose(sourceFile);
        return 1;
    }

    // 逐个字节地将源文件内容写入目标文件
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destFile);
    }

    printf("文件下载成功!\n");

    // 关闭文件
    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

以上代码实现了将一个名为source.txt的文件上传到服务器(创建一个名为destination.txt的文件),以及将服务器上的source.txt文件下载到本地(创建一个名为destination.txt的文件)。你可以根据实际情况修改文件名和路径。

0