gpt4 book ai didi

c - fread 不会对缓冲区进行更改 (C)

转载 作者:行者123 更新时间:2023-11-30 15:22:51 24 4
gpt4 key购买 nike

在进行必须解密二进制文件“imagen.png”的练习之前,我正在用 fread 进行一些实验。

在下面的代码中,我尝试将“imagen.png”的前 40 个字节存储在数组 v[] 中。问题是 v[] 中没有进行任何更改。之前,前两个值是5,剩下的8个都是垃圾。之后,同样适用。

我做错了什么?

unsigned int v[10];
v[0] = 5;
v[1] = 5;

//Here I display the content of the array v[]
int j;
for (j = 0; j < 10; j++){
printf("v-->%d\n", v[j]);
}

FILE *fp = NULL;
fp = fopen("C:\\imagen.png", "rb");

//Here I read the first 10 blocks of 4 bytes into the array v[]
if (fp != NULL){
fread(v, sizeof(unsigned int), 10, fp);
}else{
printf("error in opening file!\n");
}
fclose(fp);

//I display the content of array v[] again
for (j = 0; j < 10; j++){
printf("v-->%d\n",v[j]);
}

最佳答案

fopen 之后的测试应该是

int cnt= -1;
FILE *fp = fopen("C:\\imagen.png", "rb");
if (fp == NULL){
perror("fopen imagen.png");
exit(EXIT_FAILURE);
} else {
cnt = fread(v, sizeof(unsigned int), 10, fp);
if (cnt<0) {
perror("fread failed");
exit(EXIT_FAILURE);
}
/// use cnt cleverly ....
}

fread 正在返回计数。你应该测试一下。所以使用cnt

关于c - fread 不会对缓冲区进行更改 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29009095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com