可能重复:
C编程将一定数量的字节打印到屏幕
我想从一个文件中读取partSize字节数,该文件可以是任何类型,并将读取的字节数打印到已经存在的新文件中。我写的程序似乎写得比预期的要少,并且出现了分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define PERMS 0777
#include <errno.h>
int main()
{
int createDescriptor;
int openDescriptorOriginal;
int closeCreateDescriptor;
char fileNameOriginal[15]="picture.jpg";
//char fileNameOriginal[15]="myFile.txt";
//char fileNameNew[15]="NEWFILE.txt";
char fileName[15]="NEWFILE.jpg";
int parts;
int partSize;
parts=2;
int bytesRemaining;
int partNumber;
char BUFFER[512];
int readDescriptor;
int openDescriptor;
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: %sn",(char *)strerror(errno));
exit(1);
}
int originalFileSize=buf.st_size;
printf("The file is %d Bytes large.n",originalFileSize);
partSize=((originalFileSize+parts)-1)/parts;
printf("Each part is %.9f Kilobytes large.n",(double)partSize/1024 );
partNumber=1;
printf("Part number: %dn", partNumber);
if ((openDescriptor = open(fileName, O_WRONLY )) == -1)
{
printf("Error creating %sn", fileName);
exit(EXIT_FAILURE);
}
ssize_t count, total;
total = 0;
char *bufff = BUFFER;
while (partSize) {
count = read(openDescriptorOriginal, bufff, partSize);
if (count < 0) {
// handle error
break;
}
if (count == 0)
break;
bufff += count;
total += count;
partSize -= count;
}
write (openDescriptor, BUFFER, total);
printf("n");
return 0;
}
一些初始问题:
- 在open((中添加CREAT标志,以防文件不存在
- partSize不应调整
取出你调整零件尺寸的线,它应该可以工作。
int bytesReceived;
.... open files ....
while ((bytesReceived = read(openDescriptorOriginal, BUFFER, sizeof(BUFFER)) > 0) {
if (bytesReceived != write(openDescriptor, BUFFER, bytesReceived) {
printError(...);
}
}