如何读取文件的位并将其写入其他地方以在c中重新生成文件



myfile.txt文件为例。

我如何读取这个文件的位(1和0)并将它们写在C中的其他地方以获得确切的myfile.txt

简单地说,我想知道如何通过在c中读取和重写它们的1和0来重新生成文件。

您正在询问如何将整个文件读入内存。这是通过在循环中调用read来完成的。

#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE ...
// Returns 0 on success.
// Returns -1 and errno set on error.
int read_file( int fd, char **buf_ptr, size_t *buf_size_ptr )
*buf_ptr      = NULL;
*buf_size_ptr = 0;
char *buf = malloc( CHUNK_SIZE );
if ( !buf )
goto ERROR1;
size_t total_bytes_read = 0;
while ( 1 ) {
ssize_t bytes_read = read( fd, buf + total_bytes_read, CHUNK_SIZE );
if ( bytes_read == -1 )
goto ERROR2;
if ( bytes_read == 0 )
break;
total_bytes_read += bytes_read;
char *tmp = realloc( buf, total_bytes_read + CHUNK_SIZE );
if ( !tmp )
goto ERROR2;
buf = tmp;
}
{
char *tmp = realloc( buf, total_bytes_read );
if ( tmp ) {
buf = tmp;
}
*buf_ptr      = buf;
*buf_size_ptr = total_bytes_read ;
return 0;
ERROR2:
free( buf );
ERROR1:
return -1;
}

int main( void ) {
int fd = ...;
char *buf;
size_t buf_size;
if ( read_file( ..., &buf, &buf_size ) == -1 ) {
perror( NULL );
exit( EXIT_FAILURE );
}
// Do something with buf...
free( buf );
return EXIT_SUCCESS;
}

重新生成文件只是将缓冲区写入磁盘。

// Returns 0 on success.
// Returns -1 and errno set on error.
int write_file( int fd, const char *buf, size_t buf_size ) {
while ( buf_size > 0 )  {
ssize_t bytes_written = write( fd, buf, buf_size );
if ( bytes_written == -1 )
return -1
buf      += byte_written;
buf_size -= byte_written;
}
return 0;
}

其他所有人都明确表示,在C(以及任何其他非面向硬件的编程语言)中,您需要将字节作为最小单位来处理。

如果你想"玩弄比特",你可以读取字节,然后从中提取单个比特:

#include <stdio.h>
#include <stdbool.h>
int readbit(FILE *f)
{
static int buffer;
static int n = 0;

if (n == 0) {
buffer = fgetc(f);
if (buffer == EOF) {
return EOF;
}
n = 8;
}
return (buffer >> --n) & 1;
}
int main(void) 
{
for (int i = 0, bit; (bit = readbit(stdin)) != EOF; ++i) {
printf("%d%c", bit, ((i + 1) % 8 == 0)*' ');
}
return 0;
}

这里有一个简单的函数"读取位"从一个文件。如何?它读取并缓冲单个字节,然后返回该字节的一位。

main函数使用它来读取stdin,并将其以文本二进制形式发送到标准输出。如果你用"a0"它发送给stdout"00100000 01100001 00110000 ",即这三个字节的二进制表示(空格的数字代码为32,a为97,0为48)。

在ideone.com上试一下。

免责声明:我并不是说这是一个生产就绪的函数,也不是说在函数中使用静态变量是一个好主意。但它使这里的一切都简单了。

相关内容

最新更新