如何在 C 中逐字节或以块的形式将 () 写入文件

How to write() to a file byte by byte or in chunks in C

我正在尝试逐字节、2 字节、4 字节等以块的形式写入文件。我目前有此代码,但卡住了。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){

    char buf[1];

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);

    fread = read(infile, buf, 1);
    printf("%s\n", buf);
    write(outfile);
    close(infile);
    close(outfile)

}

在您当前的代码中,您读取了 1 个字节,然后使用 %s 打印它。那行不通的。 %s 用于打印字符串,字符串必须以零结尾,但使用 read 时不会得到以零结尾的字符串(此外,数组 buf 只能包含一个空字符串) .我假设您想打印您阅读的数据,所以请这样做:

printf("%c\n", buf[0]);

要读取整个文件,你需要一个循环:

while((fread = read(infile, buf, 1)) > 0)
{
    printf("%c\n", buf[0]);
}

关于块大小,您只能设置最大值,但 read 可能 return 更少的字节。所以喜欢:

#define MAX_BYTES_IN_A_SINGLE_READ 4

设置最大块大小并像这样使用它:

char buf[MAX_BYTES_IN_A_SINGLE_READ];
ssize_t fread;
while((fread = read(infile, buf, MAX_BYTES_IN_A_SINGLE_READ)) > 0)
{
    for (ssize_t i = 0; i < fread; ++i)
    {
        printf("%c\n", buf[i]);
    }
}

首先,我看不到你在哪里声明了 fread 变量,

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){

    char buf[1];

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);

    fread = read(infile, buf, 1); // here fread var !!?
    printf("%s\n", buf);
    write(outfile);
    close(infile);
    close(outfile)

}

而且这不是写入文件的方式,如果你编译成功那么按照这个你就可以只写入一个字节了。你必须实现一个循环 for 循环或 while 循环,以便将所有字节从一个文件写入另一个文件,如果我没弄错的话。

我在这里假设您正在尝试将数据逐字节地从一个文件写入另一个文件,因此根据这个假设,这里是在您的程序中进行一些更改的工作代码..

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>


int main(int argc, char* argv[]){
    int fread =0;
    char buf[1]; 

    //creating output file
    int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);

    int infile = open(argv[2], O_RDONLY);
    
    while(fread = read(infile, buf, 1)){ //change here number of bytes you want to read at a time and don't forget to change the buffer size too :)
    printf("%s\n", buf);
    write(outfile, buf, fread);
   }
    close(infile);
    close(outfile)

}