用C语言写一个程序自动将一个文件夹里所有CSV文件转换为unicode后另存到另一个文件夹
时间: 2023-12-10 20:02:57 浏览: 150
以下是一个基于C语言实现的自动将一个文件夹里所有CSV文件转换为Unicode编码后另存到另一个文件夹的程序示例。该示例使用了Windows API,所以仅适用于Windows系统。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <locale.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[]) {
setlocale(LC_ALL, "chs");
char *input_folder = "input_folder";
char *output_folder = "output_folder";
if (!CreateDirectoryA(output_folder, NULL)) {
DWORD error = GetLastError();
if (error != ERROR_ALREADY_EXISTS) {
printf("Failed to create output folder. Error code: %d\n", error);
return 1;
}
}
char input_pattern[MAX_PATH];
snprintf(input_pattern, MAX_PATH, "%s\\*.csv", input_folder);
WIN32_FIND_DATAA find_data;
HANDLE find_handle = FindFirstFileA(input_pattern, &find_data);
if (find_handle == INVALID_HANDLE_VALUE) {
printf("Failed to find input files. Error code: %d\n", GetLastError());
return 1;
}
do {
if (strcmp(find_data.cFileName, ".") == 0 ||
strcmp(find_data.cFileName, "..") == 0) {
continue;
}
char input_file[MAX_PATH];
snprintf(input_file, MAX_PATH, "%s\\%s", input_folder, find_data.cFileName);
FILE *input_fp = fopen(input_file, "r");
if (input_fp == NULL) {
printf("Failed to open input file %s\n", input_file);
continue;
}
char output_file[MAX_PATH];
snprintf(output_file, MAX_PATH, "%s\\%s", output_folder, find_data.cFileName);
FILE *output_fp = fopen(output_file, "w");
if (output_fp == NULL) {
printf("Failed to open output file %s\n", output_file);
fclose(input_fp);
continue;
}
char buffer[BUFFER_SIZE];
size_t read_len;
while ((read_len = fread(buffer, 1, BUFFER_SIZE, input_fp)) > 0) {
wchar_t wide_buffer[BUFFER_SIZE];
int wide_len = MultiByteToWideChar(CP_ACP, 0, buffer, read_len, wide_buffer, BUFFER_SIZE);
if (wide_len == 0) {
printf("Failed to convert input buffer to wide string. Error code: %d\n", GetLastError());
fclose(input_fp);
fclose(output_fp);
remove(output_file);
continue;
}
char unicode_buffer[BUFFER_SIZE];
int unicode_len = WideCharToMultiByte(CP_UTF8, 0, wide_buffer, wide_len, unicode_buffer, BUFFER_SIZE, NULL, NULL);
if (unicode_len == 0) {
printf("Failed to convert wide buffer to Unicode string. Error code: %d\n", GetLastError());
fclose(input_fp);
fclose(output_fp);
remove(output_file);
continue;
}
size_t write_len = fwrite(unicode_buffer, 1, unicode_len, output_fp);
if (write_len != unicode_len) {
printf("Failed to write output buffer. Error code: %d\n", GetLastError());
fclose(input_fp);
fclose(output_fp);
remove(output_file);
continue;
}
}
fclose(input_fp);
fclose(output_fp);
} while (FindNextFileA(find_handle, &find_data) != 0);
FindClose(find_handle);
return 0;
}
```
这段代码仅供参考,具体实现可能需要根据您的具体需求进行修改。同时,需要注意一些细节问题,例如异常处理、文件路径处理等。
阅读全文