读取文件并输出,输出时将小写字母转为大写

本文介绍了一个使用C语言实现的文件处理程序,通过调用stat()、fopen()等函数读取文件内容,并将所有小写字母转换为大写进行输出。文章详细展示了从文件属性获取到内容读取直至字符转换的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、获取文件属性(检查文件):stat()

              struct stat buf_stat;

stat("temp.txt", &buf_stat);// #include <sys/stat.h>

// buf_stat.st_size

2、打开文件:fopen()

FILE *fp;

fp = fopen("temp.txt", "rb");

3、申请内存,并读取文件内容至该内存空间

char *p;

p = (char *)malloc(sizeof(char) * (buf_stat.st_size + 1));// #include <stdlib.h>

len = fread(p, sizeof(char), buf_stat.st_size, fp);

  *(p + len) = '\0';

4、逐个字符地输出文件内容,并将小写字母转为大写

       char * q = p;
        while(*q != '\0')
        {
                if(('a'<=*q) && (*q<='z'))
                        *q -= 32;
                write(STDOUT_FILENO, q++, 1); // #include <unistd.h>
        }

5、出错处理

fprintf(stderr, "%s\n", strerror(errno));#include <errno.h>

perror("ERROR: ... ");

源代码:

  1 /*
  2  * FILE: p19_file.c
  3  * DATE: 20180106
  4  * --------------
  5  * DESCRIPTION: stat, fopen,
  6  * malloc, fread, perror, strerror(errno)
  7  * 读取文件内容,输出时将小写字母转换成大写字母
  8  */
  9 
 10 #include <stdio.h>
 11 #include <stdlib.h>     // malloc, free
 12 #include <sys/stat.h>   // stat
 13 #include <errno.h>      // strerror(errno)
 14 #include <unistd.h>     // STDOUT_FILENO
 15 
 16 int convert(void)
 17 {
 18         FILE *fp;
 19         struct stat buf_stat;
 20 
 21         char *p, *q;
 22         int len;
 23 
 24         if(stat("temp.txt", &buf_stat) < 0)
 25         {
 26                 printf("%s\n", strerror(errno));
 27                 return -1;
 28         }
 29         fp = fopen("temp.txt", "r");
 30         if(fp == NULL)
 31         {
 32                 printf("%s\n", strerror(errno));
 33                 return -2;
 34         }
 35         p = (char *)malloc(sizeof(char) * (buf_stat.st_size + 1));
 36         if(p == NULL)
 37         {
 38                 fclose(fp);
 39                 perror("ERROR: malloc");
 40                 return -3;
 41         }
 42         len = fread(p, sizeof(char), buf_stat.st_size, fp);
 43         if(len < 0)
 44         {
 45                 free(p);
 46                 fclose(fp);
 47                 perror("ERROR: fread, fail to read");
 48                 return -4;
 49         }
 50         *(p + len) = '\0';
 51         q = p;
 52         while(*q != '\0')
 53         {
 54                 if(('a'<=*q) && (*q<='z'))
 55                         *q -= 32;
 56                 //printf("%c", *q++);
 57                 write(STDOUT_FILENO, q++, 1);
 58         }
 59         free(p);
 60         fclose(fp);
 61         return 0;
 62 }
 63 
 64 int main(void)
 65 {
 66         convert();
 67         return 0;
 68 }
编译执行:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值