C编程打印一定量的字节到文件

时间:2013-01-02 21:42:13

标签: c file

  

可能重复:
  C programming print a certain amount of bytes to screen

我想从一个文件中读取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: %s\n",(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: %d\n", partNumber);

if ((openDescriptor = open(fileName, O_WRONLY )) == -1)
{
printf("Error creating %s\n", 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;
}

2 个答案:

答案 0 :(得分:0)

一些初步问题:

  • 如果文件不存在,则将CREAT标志添加到open()。
  • partSize不应调整

取出调整partSize的行,它应该可以工作。

答案 1 :(得分:0)

int bytesReceived;
.... open files ....
while ((bytesReceived = read(openDescriptorOriginal, BUFFER, sizeof(BUFFER)) > 0) {
    if (bytesReceived != write(openDescriptor, BUFFER, bytesReceived) {
        printError(...);
    }
}