用c语言实现电子相册循环代码
时间: 2023-10-26 19:06:08 浏览: 122
以下是一个简单的循环代码示例,可以用来实现电子相册中的图片切换功能:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <graphics.h>
#define MAX_IMAGES 1000
#define MAX_FILENAME 256
char image_filenames[MAX_IMAGES][MAX_FILENAME];
int num_images = 0;
int current_image = 0;
void load_images()
{
DIR *dir;
struct dirent *ent;
char *ext;
dir = opendir(".");
if (dir == NULL)
return;
while ((ent = readdir(dir)) != NULL) {
ext = strrchr(ent->d_name, '.');
if (ext != NULL && (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0 ||
strcmp(ext, ".png") == 0 || strcmp(ext, ".bmp") == 0)) {
strncpy(image_filenames[num_images], ent->d_name, MAX_FILENAME);
num_images++;
}
}
closedir(dir);
}
void draw_image(char *filename)
{
cleardevice();
readimagefile(filename, 0, 0, getmaxx(), getmaxy());
}
int main()
{
int gd = DETECT, gm;
int key;
initgraph(&gd, &gm, "");
load_images();
if (num_images == 0) {
printf("No images found.\n");
getch();
return 0;
}
draw_image(image_filenames[current_image]);
while (1) {
key = getch();
if (key == 'q')
break;
if (key == KEY_LEFT && current_image > 0) {
current_image--;
draw_image(image_filenames[current_image]);
}
if (key == KEY_RIGHT && current_image < num_images - 1) {
current_image++;
draw_image(image_filenames[current_image]);
}
}
closegraph();
return 0;
}
```
这段代码通过load_images函数扫描当前目录下的图片文件,将其文件名存储在image_filenames数组中。接着,在主循环中,通过getch函数获取用户输入的按键,如果是左箭头或右箭头,则切换当前显示图片,并调用draw_image函数将其显示在窗口中。用户可以通过按下q键来退出程序。
阅读全文