【文档创建日期:2010-05-30】
001 // P122: 三、上机题 3
002
003 // test03-03.c
004
005 // Header files included.
006 #include <stdio.h>
007 #include <stdlib.h>
008 #include <string.h>
009
010 #include <sys/types.h>
011 #include <sys/stat.h>
012 #include <fcntl.h>
013 #include <unistd.h>
014
015 // Conditional compilation.
016 #ifndef _MAX_DATA_TYPE_
017 #define _MAX_DATA_TYPE_
018
019 // Macro definition.
020 #define MAXSIZE 1000
021 #define BUFFSIZE 10
022
023 #endif // #define _MAX_DATA_TYPE_
024
025 #ifndef _DISTANCE_DATA_TYPE_
026 #define _DISTANCE_DATA_TYPE_
027
028 // Macro definition.
029 #define DIST 0
030
031 #endif // #define _DISTANCE_DATA_TYPE_
032
033 // No.1: Subroutine:
034 void char_convert ( char *data, const unsigned int datasize )
035 {
036 unsigned int i = 0;
037
038 for ( i=0; i<datasize; i++ )
039 {
040 if ( ('a' <= data[i]) && (data[i] <= 'z') )
041 {
042 data[i] = data[i] - ('a' - 'A');
043 }
044 }
045 }
046
047 // Main function's declaration.
048 int main ( int argc, char *argv[] )
049 {
050 unsigned int fd, count = 0;
051 char buffer[BUFFSIZE], *temp = NULL;
052
053 if ( argc != 2 )
054 {
055 printf ( "Usage: convertchar <filename>/n" );
056 return (1);
057 }
058
059 temp = (char *) malloc ((BUFFSIZE + 1) * sizeof(char));
060 if ( temp == NULL )
061 {
062 printf ( "Insufficient memory!/n" );
063 return (2);
064 }
065 temp[BUFFSIZE] = '/0';
066
067 if ( (fd = open(argv[1], O_RDWR, NULL)) == -1 )
068 {
069 printf ( "Open file: %s failed!/n", argv[1] );
070 return (3);
071 }
072 printf ( "Open file: %s succeed!/n", argv[1] );
073
074 // 在处理该文件之前先查看文件的内容
075 while ( (count = read(fd, buffer, BUFFSIZE)) > 0)
076 {
077 memcpy(temp, buffer, count);
078 if ( count == BUFFSIZE )
079 {
080 printf ( "%s", temp );
081 fflush (NULL);
082 }
083 else if ( count < BUFFSIZE )
084 {
085 temp[count] = '/0';
086 printf ( "%s", temp );
087 fflush (NULL);
088 }
089 }
090 printf ( "/n-------------------- After change --------------------/n" );
091
092 // 对文件内部的读取指针进行回位
093 lseek (fd, DIST, SEEK_SET);
094
095 // 查看处理完成之后的文件的内容,同时把该内容写回硬盘
096 while ( (count = read(fd, buffer, BUFFSIZE)) > 0)
097 {
098 // 转换大小写
099 char_convert (buffer, BUFFSIZE);
100 memcpy(temp, buffer, count);
101 // 修改文件内容的指针回位到被读取的count位置的初始处
102 lseek (fd, -count, SEEK_CUR);
103
104 if ( write(fd, buffer, count) != count )
105 {
106 printf ( "Write file: %s error!/n", argv[1] );
107 return (4);
108 }
109
110 if ( count == BUFFSIZE )
111 {
112 printf ( "%s", temp );
113 fflush (NULL);
114 }
115 else if ( count < BUFFSIZE )
116 {
117 temp[count] = '/0';
118 printf ( "%s", temp );
119 fflush (NULL);
120 }
121 }
122 printf ( "/n" );
123 printf ( "Convert the characters succeed!/n" );
124
125 close (fd);
126 free (temp);
127
128 return (0);
129 }
130
131 // test03-03.c The end.
132