【发布时间】:2015-08-19 19:27:31
【问题描述】:
我必须打开/读取一个 ascii 艺术文件(图片) 并要求我将图像的宽度和高度返回给主程序,然后要求我通过指针将图片数据传回。这是我必须使用的函数原型:
unsigned char *foo(char *filename, int *width, int *height)
在 foo 内部,我必须使用一个动态的字符数组 存储图像数据。我需要使用 fread() 来阅读 那个数据。我还必须考虑每行末尾的回车。
打开并读取数据后,将其传回主程序。然后主程序必须创建一个动态二维数组来存储图像,复制一维数组 进入二维数组,并将图像显示在屏幕上。
图像文件名:data.txt
我的代码:
#include <stdio.h>
#include <stdlib.h>
void readDimension(FILE *inFile, int *width, int *height)
{
int i;
for (i = 0; i < 2; i++)
{
if (i == 0)
{
fscanf(inFile, "%d", width);
}
if (i == 1)
{
fscanf(inFile, "%d", height);
}
}
}
unsigned char *foo(char *filename, int *width, int *height)
{
FILE *inFile = fopen(filename, "rb");
readDimension(inFile, width, height);
unsigned char *ret = malloc(*width * *height);
fread(ret, 1, *width * *height, inFile);
fclose(inFile);
return ret;
}
int main(int argc, char** argv)
{
FILE *inFile;
int width, height;
unsigned char art;
if (argc == 1)
{
printf("Please specify a file name.\n");
}
else if (argc == 2)
{
inFile = fopen(argv[1], "rb");
if (inFile != NULL)
{
fclose(inFile);
art = foo(argv[1], &width, &height);
int n = sizeof(art);
printf("Data in Array: \\%c \n", art);
printf("Size of Array: %d \n", n);
}
else
{
printf("Error: File Not Found %s", argv[1]);
}
}
printf("Width: %d\n", width); // Testing
printf("Height: %d\n", height); // Testing
}
【问题讨论】:
-
1)
unsigned char art;应该是unsigned char *art; -
2)
fscanf(inFile, "%d", height);-->fscanf(inFile, "%d%*c", height); -
@BLUEPIXY 为什么是
%*c? -
%*c跳过换行符。 -
郑重声明,您的文件是 text 文件,而不是二进制文件。 “ASCII”可能是您的第一个线索,处理行终止符的需要当然应该达成交易。
标签: c arrays image binary unsigned