我尝试从此代码读取文件。我试图加载图像并将它们作为字符串存储到我的程序中,因此以后可以使用fprintf将相同的图像创建到新文件中。我不允许使用某些文件复制;我需要将文件作为字符串加载,并在以后将其写入新文件。我正在尝试拥有一个char数组,并且由于一个char是一个字节,因此该数组与文件大小一样长,并且char数组的每个元素都对应于菱形块纹理的一个字节,我也想能够将代码中的字符串写入新文件,并可以使用图像查看器打开另一个菱形块。
#include <stdio.h>
#include <stdlib.h>
char Contents[468];
int main(int argc, char *argv[]) {
char *WD = getenv("HOME");
char Path[strlen(WD)+strlen("/Desktop/diamond_block.png")+1];
sprintf(Path, "%s/Desktop/diamond_block.png", WD);
FILE *File = fopen(Path, "r");
fscanf(File, "%s", Contents);
printf(Contents);
}
结果只有四个字母âPNG
,应该是数百个字符,这意味着该文件没有被完全读取。我怀疑它早已被某个终止字符终止了,但是我该如何解决我的问题呢?
答案 0 :(得分:2)
这是对您的问题的非常基本的答案。使用下面的代码,您可能会明白您的问题所在。这段代码需要进行良好的审查,以拦截使用的函数可能返回的所有错误。顺便说一句...享受它!
代码将整个文件fname
加载到char
数组imgMem
中。它计算变量n
的文件尺寸,为数组imgMem
(malloc
)分配内存,然后将整个文件加载到imgMem
(fread
)。
然后代码以两种格式写入文件的前30个字节:
.
)代码在这里:
#include <unistd.h>
#include <stdio.h>
#include <malloc.h>
int main(void)
{
const char * fname = "/home/sergio/Pictures/vpn.png";
FILE * fptr;
char * imgMem=NULL;
long n;
int i;
fptr=fopen(fname, "r");
//Determine the file dimension
fseek(fptr,0,SEEK_END); n=ftell(fptr);
//Set the file cursor to the beginning
fseek(fptr,0,SEEK_SET);
printf("The file is %lu byte long.\n\n",n);
//Allocate n bytes to load the file
imgMem = malloc((size_t)n);
//Load the file
fread(imgMem,(size_t)n,1,fptr);;
for(i=0; i<30; i++) {
printf("[%02X %c] ",
(unsigned char)imgMem[i],
(imgMem[i]>31 && imgMem[i]<127)?
imgMem[i]:'.'
);
if ((i+1)%8==0)
puts("");
}
puts("");
free(imgMem);
fclose(fptr);
return 0;
}