-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadfile.c
More file actions
65 lines (56 loc) · 1.56 KB
/
Copy pathreadfile.c
File metadata and controls
65 lines (56 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<errno.h>
/* argv[1]: filename :: the file which need to be read
* argv[2]: offset :: the number of bytes off file'head
* argv[3]: number :: the number of bytes that wanted to be read
*
*/
void usage()
{
printf("\033[31musage:\033[0m\n");
printf("\033[31margv[1]: filename :: the file which need to be read.\033[0m\n");
printf("\033[31margv[2]: offset :: the number of bytes off file'head.\033[0m\n");
printf("\033[31margv[3]: number :: the number of bytes that wanted to be read.\033[0m\n\n");
}
int main(int argc, char* argv[])
{
if (argc!=4)
{
printf("the command isnot correct.\n");
usage();
exit(1);
}
#define nBuffer 4096
char buffer[nBuffer];
int fd;
/* open file */
if ( (fd=open(argv[1],O_RDONLY))==-1)
{
//perror("open file error!"); the next is better.
fprintf(stderr, "open file %s error! %s\n", argv[1], strerror(errno));
exit(1);
}
/*seek the file */
if(lseek(fd,atoi(argv[2]),SEEK_SET) == -1)
{
fprintf(stderr, "lseek file %s error! %s\n", argv[1], strerror(errno));
close(fd);
exit(1);
}
int nRead=0;
memset(buffer,0,nBuffer);
/* read file */
if( (nRead=read(fd,buffer,atoi(argv[3]))) == -1)
{
fprintf(stderr, "read file %s error! %s\n", argv[1], strerror(errno));
close(fd);
exit(1);
}
close(fd);
printf("nRead=%d\n",nRead);
printf("%s\n",buffer);
return 1;
}