Skip to content

Commit

Permalink
finish large-file homework
Browse files Browse the repository at this point in the history
  • Loading branch information
guijiangheng committed Dec 20, 2016
1 parent e900a0c commit 8772613
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
2 changes: 1 addition & 1 deletion 04/getopt.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* 初次调用getopt时,optind=1
* 当选项是紧密连接的,形如-abc,则optind会三次指向该字
* 同时函数内部会有状态标志,从而从这一个字中解析出三个选项a,b,c
* 当选项解析完后,optind就指向了第一个参数,[opting, argc)就是命令行的所有参数
* 当选项解析完后,optind就指向了第一个参数,[optind, argc)就是命令行的所有参数
*/

#include <stdio.h>
Expand Down
51 changes: 51 additions & 0 deletions 04/large-file.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* 64位系统默认支持LFS了
* ./a.out test 10000000000
* ls -lh
* 将看到test文件大小为9.4G
* 只有在移动偏移位置至文件末尾之后,且进行写之后才会有空洞
* gcc -m32 large-file.c会报编译错误,不知为何
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <fcntl.h>

#include <unistd.h>

char errMsg[1024];

int main(int argc, char** argv) {
if(argc != 3 || strcmp(argv[1], "--help") == 0) {
fprintf(stderr, "error, usage: %s pathname offset\n", argv[0]);
exit(1);
}

int fd = open(argv[1], O_CREAT | O_RDWR, S_IWUSR | S_IRUSR);
if(fd == -1) {
sprintf(errMsg, "open %s failed", argv[1]);
perror(errMsg);
exit(1);
}

off_t offset = atoll(argv[2]);
if(lseek(fd, offset, SEEK_SET) == -1) {
perror("seek failed");
exit(1);
}

if(write(fd, "test", 4) == -1) {
perror("write failed");
exit(1);
}

if(close(fd) == -1) {
sprintf(errMsg, "close %s failed", argv[1]);
perror(errMsg);
exit(1);
}

return 0;
}

0 comments on commit 8772613

Please sign in to comment.