include stdio h include stdlib h include errno
ファイルを読み込んで、その内容を表示するプログラムを作成せよ。 #include <stdio. h> #include <stdlib. h> #include <errno. h> #include <sys/types. h> #include <sys/stat. h> #include <fcntl. h> main(narg, arg) int narg; char **arg; { int fd; char ch; fd=open(arg[1], O_RDONLY); if(fd<0){ perror("File Name"); exit(EXIT_FAILURE); } while(read(fd, &ch, sizeof(char))) printf("%c", ch); close(fd); }
キーボードから文字を入力して、その内容をファイルに書き込むプログラムを作成せよ。 #include <stdio. h> #include <stdlib. h> #include <errno. h> while(1){ ch=getchar(); if(ch==EOF) break; #include <sys/types. h> #include <sys/stat. h> #include <fcntl. h> main(narg, arg) int narg; char **arg; { int fd; char ch; write(fd, &ch, sizeof(char)); } close(fd); } fd=open(arg[1], O_WRONLY|O_APPEND |O_CREAT); if(fd<0){ perror("File Name"); exit(EXIT_FAILURE); }
ファイルから数字を読み込んで、ソートするプログラムを作成せよ。 #include <stdio. h> #include <stdlib. h> #include <errno. h> main(narg, arg) int narg; char **arg; { FILE *fd; char ch; int num[1024]; int n=0; int i, j; fd=fopen(arg[1], "r"); if(fd == NULL){ perror("File Name"); exit(EXIT_FAILURE); } for(i=0; i<n-1; i++) for(j=i+1; j<n; j++){ if(num[i] > num[j]){ int tmp; tmp=num[j]; num[j]=num[i]; num[i]=tmp; } } while(1){ char buf[128]; if(fgets(buf, 128, fd)==NULL) break; } sscanf(buf, "%d", &num[n]); n++; printf("n. Aftern"); for(i=0; i<n; i++) printf("%dn", num[i]); printf("Beforen"); for(i=0; i<n; i++) printf("%dn", num[i]); fclose(fd); }
- Slides: 6