我正在尝试一些 C 语言的文件操作技术,因此我编写了一个简单的程序,它将文件作为输入并将其复制到一个空文件中。我在“二进制”和“读取”模式下使用 fopen() 打开要读取的文件,使用 fgetc() 逐一读取所有字节,并将它们写入我想要写入的文件中,该文件是在“写入”和“读取”模式下打开的二进制模式。当复制操作完成(EOF)时,我对两个文件调用 fclose() 并终止程序。
问题是:文本文件一切正常,但是当我尝试以不同格式(如 pdf 或 jpeg)复制文件时,出现段错误。由于代码非常短且简单,我怀疑这个问题是由于我对用 C 读写这些文件格式缺乏了解造成的,而不是代码中的错误。
欢迎任何建议和想法,如果您怀疑我的代码可能做错了什么,我也可以发布。
编辑:好的,所以我可能搞乱了代码,如下:
#include <stdio.h>
#include <stdlib.h>
#define MAXCHAR 10000000
int main( int argc, char** argv)
{
if( argc != 3)
{
printf( "usage: fileexer1 <read_pathname> <write_pathname>");
exit( 1);
}
FILE* file_read;
FILE* file_write;
int nextChar;
char readBuffer[MAXCHAR];
int valid = 0;
// These hold the path addresses to the files to be read and written
char* read_file_path = argv[1];
char* write_file_path = argv[2];
// The file to be read is opened in 'read' and 'binary' modes
file_read = fopen( read_file_path, "rb");
if( !file_read)
{
perror( "File cannot be opened for reading");
exit( 1);
}
// The file to be written into is opened in 'write' and 'binary' modes
file_write = fopen( write_file_path, "wb");
if( !file_write)
{
perror( "File cannot be opened for writing");
exit( 1);
}
nextChar = fgetc( file_read);
while( nextChar != EOF)
{
readBuffer[valid] = (char) nextChar;
valid++;
nextChar = fgetc( file_read);
}
int i;
for( i = 0; i < valid; i++)
{
fputc( readBuffer[i], file_write);
}
fclose( file_read);
fclose( file_write);
return 0;
}
最佳答案
我猜你的代码有问题,因为编写任何二进制类型文件都没有什么奇怪的。二进制就是二进制。下面是一些将名为 1.jpg 的图像复制到 2.jpg 的代码。
int main (){
FILE *readf, *writef;
unsigned char *buffer;
unsigned long len;
int i=0;
//Open file
readf = fopen("1.jpg", "rb");
writef = fopen("2.jpg","wb");
//you should check if readf & writef were opened successfully here...
//Get file length
fseek(readf, 0, SEEK_END);
len=ftell(readf);
fseek(readf, 0, SEEK_SET);
//Allocate memory
buffer=(char *)malloc(len);
//check that buffer got memory allocated here...
fread(buffer,fileLen,sizeof(unsigned char),readf);
fwrite(buffer,fileLen,sizeof(unsigned char),writef);
//cleanup
fclose(readf);
fclose(writef);
free(buffer);
return 0;
}
关于c - 简单的文件复制,不同文件类型的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12305512/