用C语言写文件操作代码(2进制格式的文件)
时间: 2023-05-27 08:04:45 浏览: 50
以下是一个使用C语言操作二进制文件的基本示例代码:
```c
#include <stdio.h>
#define BUFFER_SIZE 1024
int main() {
FILE *file;
char buffer[BUFFER_SIZE];
int count;
// 以二进制读取方式打开文件
file = fopen("binary_file.bin", "rb");
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
// 读取文件内容并输出
while ((count = fread(buffer, sizeof(char), BUFFER_SIZE, file)) > 0) {
fwrite(buffer, sizeof(char), count, stdout);
}
// 关闭文件
fclose(file);
return 0;
}
```
该示例代码打开一个名为“binary_file.bin”的二进制文件,并将其内容输出到标准输出。使用“rb”打开文件时,“b”表示以二进制模式打开文件。然后,使用fread从文件中读取内容到缓冲区,并使用fwrite将缓冲区中的内容写入标准输出。最后,使用fclose关闭文件。
相关问题
c语言文本文件转换为二进制文件代码
Sure, 我可以为您提供有关将C语言文本文件转换为二进制文件的代码。以下是使用C语言实现的文本转二进制代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE *input_file, *output_file;
char ch;
if (argc != 3) {
printf("Usage: %s input_file output_file\n", argv[0]);
return -1;
}
input_file = fopen(argv[1], "r");
if (input_file == NULL) {
printf("Can't open input file %s\n", argv[1]);
return -1;
}
output_file = fopen(argv[2], "wb");
if (output_file == NULL) {
printf("Can't open output file %s\n", argv[2]);
return -1;
}
while ((ch = fgetc(input_file)) != EOF) {
fputc((int) ch, output_file);
}
fclose(input_file);
fclose(output_file);
return 0;
}
```
您可以使用此代码将C语言文本文件(以文本形式存储)转换为二进制文件(以二进制形式存储)。执行以下操作:
```bash
$ gcc text_to_binary.c -o text_to_binary
$ ./text_to_binary input_file output_file
```
其中,`input_file`是要转换的文本文件的路径,`output_file`是存储二进制文件的路径。完成后,您可以使用二进制文件进行其他操作。
C语言 读写二进制文件代码
你好,以下是读写二进制文件的 C 语言代码示例:
// 写入二进制文件
#include <stdio.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student stu = {"Tom", 18, 90.5};
FILE *fp = fopen("student.dat", "wb");
if (fp == NULL) {
printf("打开文件失败\n");
return 1;
}
fwrite(&stu, sizeof(struct student), 1, fp);
fclose(fp);
return ;
}
// 读取二进制文件
#include <stdio.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student stu;
FILE *fp = fopen("student.dat", "rb");
if (fp == NULL) {
printf("打开文件失败\n");
return 1;
}
fread(&stu, sizeof(struct student), 1, fp);
printf("姓名:%s\n", stu.name);
printf("年龄:%d\n", stu.age);
printf("成绩:%f\n", stu.score);
fclose(fp);
return ;
}