我编写的程序获取一个文件的大小,从该文件中读取 partSize 个字节,并将 partSize 个字节写入一个新创建的文件。问题是它只适用于小文本文件。如果我尝试使用几百行的文本文件或图片运行程序,则会出现分段错误,并且将明显少于 partSize 的字节存储到新文件中。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
int main()
{
int createDescriptor;
int openDescriptorOriginal;
int closeCreateDescriptor;
// char fileNameOriginal[] = "picture.jpg";
char fileNameOriginal[] = "myFile.txt";
int parts;
int partSize;
parts=2;
int bytesRemaining;
int partNumber;
char BUFFER[512];
int readDescriptor;
int buffer[1];
oid *pbuffer = &buffer;
int bytes, infile, outfile;
if ((openDescriptorOriginal = open(fileNameOriginal, O_RDONLY )) == -1)
{
printf("Error opening %s", fileNameOriginal);
exit(EXIT_FAILURE);
}
struct stat buf;
int r = fstat(openDescriptorOriginal, &buf);
if (r)
{
fprintf(stderr, "error: fstat: %s\n", (char *) strerror(errno));
exit(1);
}
int originalFileSize = buf.st_size;
printf("The file is %.9f bytes large.\n",(double)originalFileSize);
partSize = ((originalFileSize + parts) - 1)/parts;
printf("Part size: %.9f bytes large\n",(double)partSize);
umask(0000);
//create and open new file
if ( (outfile = open("NewPicture.jpg", O_CREAT|O_WRONLY,0777))==-1 )
{
printf("ERROR %s\n", "NewPicture.jpg");
}
ssize_t count, total;
total = 0;
char *bufff = BUFFER;
while (partSize) {
count = read(openDescriptorOriginal, bufff, partSize);
if (count < 0) {
break;
}
if (count == 0)
break;
bufff += count;
total += count;
partSize -= count;
}
write (outfile, BUFFER, total);
printf("\n");
return 0;
}