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 }
编译执行: