C语言中使用fgetc和fput转换时出现乱码的解决方法

添加以下头文件和代码

#include <fcntl.h>

// 设置输入文件为二进制模式
_setmode(_fileno(inFile), _O_BINARY);

// 设置输出文件为二进制模式
_setmode(_fileno(outFile), _O_BINARY);

问题解决!!!

本文使用的全部代码如下:

#include <stdio.h>
#include <ctype.h>
#include <fcntl.h> // Include for _O_BINARY

int upperToLower(void) {
FILE *inFile = NULL, *outFile = NULL;
int ch;
errno_t err;
// 打开输入文件
err = fopen_s(&inFile, “test.txt”, “r”);
if (err != 0) {
printf(“Error opening input file. Error code: %d\n”, err);
return -1;
}
// 设置输入文件为二进制模式
_setmode(_fileno(inFile), _O_BINARY);
// 打开输出文件
err = fopen_s(&outFile, “test2.txt”, “w”);
if (err != 0) {
printf(“Error opening output file. Error code: %d\n”, err);
if (inFile != NULL) {
fclose(inFile);
}
return -1;
}
// 设置输出文件为二进制模式
_setmode(_fileno(outFile), _O_BINARY);
// 读取并转换字符
while ((ch = fgetc(inFile)) != EOF) {
// 将大写字母转换为小写
if (isupper((unsigned char)ch)) {
ch = tolower((unsigned char)ch);
}
// 写入转换后的字符到输出文件
if (fputc(ch, outFile) == EOF) {
perror(“Error writing to output file”);
if (inFile != NULL) {
fclose(inFile);
}
if (outFile != NULL) {
fclose(outFile);
}
return -1;
}
}
// 关闭文件
if (inFile != NULL) {
fclose(inFile);
}
if (outFile != NULL) {
fclose(outFile);
}
return 0;
}

int main() {
int result = upperToLower();
if (result == 0) {
printf(“Conversion completed successfully.\n”);
} else {
printf(“An error occurred during conversion.\n”);
}
return 0;
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值