为什么这个 while 循环不能按 C 中的预期工作

问题描述 投票:0回答:1

我正在尝试编写一个程序来复制文件的内容,然后将内容放入另一个文件中。我的代码可以工作,但只复制一个字符。我认为我的 while 循环是错误的,我不知道如何修复它。你能帮我吗?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    // Check if the user provided exactly two filenames
    if (argc != 3) {
        printf("Usage: %s [source_file] [destination_file]\n", argv[0]);
        return 1;  // Return an error code to indicate failure
    }

    // Open the source file for reading
    FILE *source = fopen(argv[1], "rb");

    if (source == NULL) {
        printf("Error: Unable to open the source file.\n");
        return 1;
    }

    // Open the destination file for writing
    FILE *destination = fopen(argv[2], "wb");

    if (destination == NULL) {
        printf("Error: Unable to open the destination file.\n");
        fclose(source); // Close the source file before exiting
        return 1;
    }

    char buffer[1024];
    size_t bytes_read;

    // Copy the contents of the source file to the destination file
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) {
        fwrite(buffer, 1, bytes_read, destination);
    }

    // Close both files
    fclose(source);
    fclose(destination);

    printf("File copied successfully.\n");
    return 0;
}
c file while-loop copy
1个回答
0
投票

您的问题可能与您在 fwrite 调用中将每个元素视为单个字节这一事实有关,这可能导致它一次只写入一个字符。要解决此问题,您需要修改 fwrite 调用以考虑读取的元素数量 (bytes_read) 乘以每个元素的大小。 试试这个代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    // Check if the user provided exactly two filenames
    if (argc != 3) {
        printf("Usage: %s [source_file] [destination_file]\n", argv[0]);
        return 1;  // Return an error code to indicate failure
    }

    // Open the source file for reading
    FILE *source = fopen(argv[1], "rb");

    if (source == NULL) {
        printf("Error: Unable to open the source file.\n");
        return 1;
    }

    // Open the destination file for writing
    FILE *destination = fopen(argv[2], "wb");

    if (destination == NULL) {
        printf("Error: Unable to open the destination file.\n");
        fclose(source); // Close the source file before exiting
        return 1;
    }

    char buffer[1024];
    size_t bytes_read;

    // Copy the contents of the source file to the destination file
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) {
        fwrite(buffer, 1, bytes_read, destination);
    }

    // Close both files
    fclose(source);
    fclose(destination);

    printf("File copied successfully.\n");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.