帮我写一个将文件夹下的只含一列的TXT数据文件循环出图并按自定义格式进行JPG格式保存的程序示例
时间: 2023-03-30 11:00:34 浏览: 49
好的,我可以回答这个问题。以下是一个示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gd.h>
#define MAX_FILENAME_LEN 256
#define MAX_LINE_LEN 1024
int main(int argc, char *argv[])
{
char input_folder[MAX_FILENAME_LEN];
char output_folder[MAX_FILENAME_LEN];
char input_filename[MAX_FILENAME_LEN];
char output_filename[MAX_FILENAME_LEN];
FILE *input_file;
gdImagePtr image;
int width, height;
int x, y;
char line[MAX_LINE_LEN];
int value;
int max_value = ;
if (argc != 3) {
printf("Usage: %s input_folder output_folder\n", argv[]);
return 1;
}
strcpy(input_folder, argv[1]);
strcpy(output_folder, argv[2]);
// Loop through all files in input folder
DIR *dir;
struct dirent *ent;
if ((dir = opendir(input_folder)) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) { // Regular file
strcpy(input_filename, input_folder);
strcat(input_filename, "/");
strcat(input_filename, ent->d_name);
printf("Processing file %s...\n", input_filename);
// Open input file
input_file = fopen(input_filename, "r");
if (input_file == NULL) {
printf("Error: cannot open input file %s\n", input_filename);
continue;
}
// Read data from input file
max_value = ;
while (fgets(line, MAX_LINE_LEN, input_file) != NULL) {
sscanf(line, "%d", &value);
if (value > max_value) {
max_value = value;
}
}
fclose(input_file);
// Create output image
width = max_value + 1;
height = 256;
image = gdImageCreateTrueColor(width, height);
for (x = ; x < width; x++) {
for (y = ; y < height; y++) {
gdImageSetPixel(image, x, y, gdImageColorAllocate(image, 255, 255, 255));
}
}
// Draw histogram
input_file = fopen(input_filename, "r");
while (fgets(line, MAX_LINE_LEN, input_file) != NULL) {
sscanf(line, "%d", &value);
y = (int)round((double)value / (double)max_value * (double)(height - 1));
for (x = ; x <= value; x++) {
gdImageSetPixel(image, x, height - y - 1, gdImageColorAllocate(image, , , ));
}
}
fclose(input_file);
// Save output image
strcpy(output_filename, output_folder);
strcat(output_filename, "/");
strcat(output_filename, ent->d_name);
strcat(output_filename, ".jpg");
FILE *output_file = fopen(output_filename, "wb");
gdImageJpeg(image, output_file, 100);
fclose(output_file);
gdImageDestroy(image);
}
}
closedir(dir);
} else {
printf("Error: cannot open input folder %s\n", input_folder);
return 1;
}
return ;
}
```
这个程序可以循环遍历指定文件夹下的所有 TXT 文件,读取每个文件中的数据,生成对应的直方图,并将直方图以 JPG 格式保存到指定的输出文件夹中。你可以根据自己的需要进行修改和定制。