gpt4 book ai didi

使用 fread 和 fwrite 复制二进制文件

转载 作者:行者123 更新时间:2023-11-30 21:01:06 28 4
gpt4 key购买 nike

我在使用 freadfwrite 复制二进制文件时遇到问题:循环仅运行两次(40 字节),但文件长度为 160 字节:

#include <string.h>
#define PER_READ 30
int main(void)
{

char buffer[500] = { 0 };
FILE* CSV = fopen( "CSV.csv", "rb" );
FILE* csvDest = fopen( "CSVDest.csv", "wb" );
unsigned int finished = 0;
unsigned int counter = 0;
do
{
finished = fread( buffer, sizeof( char*), PER_READ, CSV );//Read all from CSV to a string name buffer
finished += PER_READ * counter;
counter++;
} while (finished == PER_READ * counter);
fwrite( buffer, sizeof( char* ), finished, csvDest );// write all to a the file CSVDest

system( "PAUSE" );
return (0);
};

最佳答案

您的实现可以是像这样的简单循环,它会重复直到没有读取任何字节。请注意,sizeof(char*) 是错误的 - 指针的大小,而 sizeof(char) 根据定义是 1

#include <stdio.h>                                              // include proper header

#define BUFFSIZE 512 // power of 2 is kind to system

int main(void)
{
char buffer[BUFFSIZE];
size_t bytes;
FILE *fin, *fou;
fin = fopen("CSV.csv", "rb");
fou = fopen("CSVDest.csv", "wb");
if(fin == NULL || fou == NULL)
return 1; // or other action
while ((bytes = fread(buffer, 1, BUFFSIZE, fin)) != 0) {
if(fwrite(buffer, 1, bytes, fou) != bytes) {
return 1; // or other action
}
}
fclose(fou);
fclose(fin);
return 0;
}

关于使用 fread 和 fwrite 复制二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37032360/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com