c语言实现,存在文件a,b,将a中的内容大写转换为小写,小写转换为大写,如果全为大写或小写,则不变,最后存入文件b中。
时间: 2023-05-28 12:01:17 浏览: 47
以下是C语言实现代码:
```
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *f1, *f2;
char ch;
// 打开文件a和文件b
f1 = fopen("a.txt", "r");
if (f1 == NULL) {
printf("无法打开文件a.txt\n");
return 0;
}
f2 = fopen("b.txt", "w");
if (f2 == NULL) {
printf("无法打开文件b.txt\n");
return 0;
}
// 逐个读取文件a中的字符,转换为大写或小写,写入文件b中
while ((ch = fgetc(f1)) != EOF) {
if (isupper(ch)) {
ch = tolower(ch);
} else if (islower(ch)) {
ch = toupper(ch);
}
fputc(ch, f2);
}
// 关闭文件a和文件b
fclose(f1);
fclose(f2);
return 0;
}
```
相关问题
c语言,将字符串中的大写字母转换为小写字母,小写字母转换为大写字母
以下是一个简单的C语言程序,可以将一个字符串中的大写字母转换为小写字母,小写字母转换为大写字母:
```
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (isupper(str[i])) {
str[i] = tolower(str[i]);
} else if (islower(str[i])) {
str[i] = toupper(str[i]);
}
}
printf("Result: %s\n", str);
return 0;
}
```
该程序使用了`ctype.h`头文件中的`isupper()`和`islower()`函数来判断字符是否为大写或小写字母,使用了`toupper()`和`tolower()`函数来将字符转换为大写或小写字母。程序先读取一个字符串,然后遍历字符串中的每一个字符,如果它是大写字母,则将其转换为小写字母,如果它是小写字母,则将其转换为大写字母。最后输出转换后的字符串。
用C语言实现统计在一个文件中,将小写字母转换为大写。(不用输入文件名)
以下是一个实现的示例代码:
```c
#include <stdio.h>
#include <ctype.h>
#define FILENAME "test.txt" // 文件名
int main() {
FILE *fp;
int c;
fp = fopen(FILENAME, "r+"); // 以读写模式打开文件
if (fp == NULL) {
printf("Failed to open file %s\n", FILENAME);
return 1;
}
// 逐个字符读取文件内容并转换为大写写入
while ((c = fgetc(fp)) != EOF) {
if (islower(c)) {
fseek(fp, -1, SEEK_CUR); // 回退一个字符位置
fputc(toupper(c), fp); // 写入大写字符
}
}
fclose(fp); // 关闭文件
return 0;
}
```
在这个示例代码中,我们首先定义了一个常量 `FILENAME`,表示文件名。然后通过 `fopen` 函数以读写模式打开文件,如果打开失败则输出错误信息并退出程序。
接着我们使用 `fgetc` 函数逐个字符读取文件内容,并判断是否为小写字母。如果是,则使用 `fseek` 函数回退一个字符位置,再使用 `fputc` 函数写入相应的大写字母。
最后使用 `fclose` 函数关闭文件,完成操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)