程序中有一个 SDL_image 的函数SDL_Surface *IMG_Load(const char *file);
它需要一个 const char *
的字符串,来读取硬盘上的图片文件。
我本地的图片文件名格式为 my1.jpg, my2.jpg, my3.jpg...,所有文件名前缀一致,数字递增。
因为需要在多个文件 / 函数中读取图片位置,我定义了一个全局数组,把文件名存储在数组中。
想到以下三种方式实现文件名读取,但觉得三种都太复杂。
第一种方式(利用指向二维数组的指针,传递给函数):
#include <cstdio>
#include <iostream>
using namespace std;
const unsigned img_num = 113;
typedef char (*img_arr)[20];
img_arr file_name(char (*arr)[20])
{
for (unsigned i = 0; i < img_num; ++i) {
sprintf(arr[i], "my%u.jpg", i);
}
return arr;
}
int main()
{
char myimg[img_num][20] = {0};
const char (*const pimg)[20] = file_name(myimg);
for (unsigned i = 0; i < img_num; ++i) {
cout << pimg[i] << endl;
}
return 0;
}
第二种(函数返回一个带二维数组的结构体,参考代码:https://www.zhihu.com/question/26780014/answer/33999913):
#include <cstdio>
#include <iostream>
using namespace std;
const unsigned img_num = 113;
struct IMG_ARR {
char img[img_num][20];
};
IMG_ARR file_name()
{
IMG_ARR arr;
for (unsigned i = 0; i < img_num; ++i) {
sprintf(arr.img[i], "my%u.jpg", i);
}
return arr;
}
int main()
{
IMG_ARR my = file_name();
for (unsigned i = 0; i < img_num; ++i) {
cout << my.img[i] << endl;
}
return 0;
}
第三种 (人工写出图片位置):
#include <iostream>
using namespace std;
const char *myimg[] = {
"my1.jpg", "my2.jpg", "my3.jpg",
// ...
};
int main()
{
for (unsigned i = 0; i < sizeof(myimg) / sizeof(*myimg); ++i) {
cout << myimg[i] << endl;
}
}
如果资源文件的数量太多,把文件名存放在数组似乎不是一个好的想法。如果为每一个函数写类似这样的代码:
char arr[20] = {0};
for (unsigned i = 0; i < 113; ++i)
sprintf(arr, "my%u.jpg", i);
也会显得很冗杂,是否有更好的方式去读取文件名?
高洛峰2017-04-17 13:43:50
Read directly vector<string> and then pass in string.c_str() to get the char* pointer
PHP中文网2017-04-17 13:43:50
C style:
#include <cstdio>
#include <iostream>
using namespace std;
const unsigned img_num = 113;
void set_filename(char *fname, unsigned i)
{
sprintf(fname, "my%u.jpg", i);
}
int main()
{
char fname[20];
for (unsigned i = 0; i < img_num; ++i) {
set_filename(fname, i);
cout << fname << endl;
}
return 0;
}
怪我咯2017-04-17 13:43:50
I think the function decomposition of each function is not appropriate.
Shouldn’t there be one function specifically responsible for traversing the file and calling other functions, and the other functions only process a single image? With this design, there is naturally no need to add file traversal code to each function, and the functional division is clearer, making it easier to do concurrency.