C 读取写入文件

标签 c file

我编写的程序获取一个文件的大小,从该文件中读取 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;

}

最佳答案

您正在使用只有 512 字节的缓冲区。

缓冲区[512];

如果该文件中的内容超出此限制,则会发生段错误。

关于C 读取写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134409/

相关文章:

C语言编程结构

c - 如何将文件中的逗号分隔行拆分为 C 中的变量?

c - 读取二进制数据C(open,read)

linux - 如何找出目录或文件所在的挂载/分区? (Linux 服务器)

c - C中的二进制补码加法溢出

c - C 中的指针作用域

c - 使用整数格式说明符而不是 short int : Why does the code behave like this?

c - 这个熟悉的函数在 C 中是如何实现的呢?

java - RandomAccessFile.seek() 如何工作?

file - LISP:如何从文件中读取内容并将其写入另一个文件?