用c写读取二进制的代码
时间: 2023-06-01 08:06:49 浏览: 47
以下是一个简单的示例代码,可以用 C 语言读取二进制文件:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
unsigned char buffer[1024];
int numbytes;
fp = fopen("binaryfile.bin", "rb"); // 打开二进制文件
if (fp == NULL) // 如果文件打开失败
{
printf("Error opening file");
return 1;
}
numbytes = fread(buffer, sizeof(unsigned char), 1024, fp); // 读取文件
for (int i = 0; i < numbytes; i++) // 遍历读取到的数据,进行处理
{
printf("%02x ", buffer[i]); // 打印十六进制值
}
fclose(fp); // 关闭文件
return 0;
}
```
相关问题
用c写读取二进制的代码,其中先获取文件的长度
以下是用C语言读取二进制文件并获取文件长度的示例代码:
```
#include <stdio.h>
int main()
{
FILE *fp;
long size;
fp = fopen("binary_file.bin", "rb");
if (fp == NULL)
{
printf("Cannot open file.\n");
return 1;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("The file size is %ld bytes.\n", size);
fclose(fp);
return 0;
}
```
请注意,本代码示例不包含错误处理和异常情况处理。更完整和健壮的代码应该进行更多的错误处理,并且应该使用更安全的文件操作函数。
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 ;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)