おはようございます
Linuxのシステムコールの勉強をしていて、cat的なものを書いてみたのですが冒頭に変な文字化けが出て失敗してしまいます。
間違っているところを指摘してもらえると嬉しいです。よろしくお願いします。
- ソースコード
c
1//test.cファイルに記載 2#include <stdio.h> 3#include <stdlib.h> 4#include <unistd.h> 5#include <sys/types.h> 6#include <sys/stat.h> 7#include <fcntl.h> 8 9static void do_cat(const char *path); 10static void die(const char *s); 11 12int main(int argc, char *argv[]){ 13 int i; 14 15 if (argc < 2) { 16 fprintf(stderr, "%s: file name not given\n", argv[0]); 17 } 18 for (i=0;i<argc;i++) { 19 do_cat(argv[i]); 20 } 21 exit(0); 22} 23 24#define BUFFER_SIZE 2048 25 26static void do_cat(const char *path) { 27 int fp; 28 char buf[BUFFER_SIZE]; 29 int n; 30 31 if ((fp = open(path, O_RDONLY)) < 0) die(path); 32 while ((n = read(fp, buf, BUFFER_SIZE)) > 0) { 33 if (write(STDOUT_FILENO, buf, n) < 0) die(path); 34 } 35 if (close(fp) < 0) die(path); 36} 37 38static void die(const char *s){ 39 fprintf(stderr, "cant open %s", s); 40 exit(1); 41}
- 結果
bash
1$ gcc -Wall test.c -o test 2$ ./test test.c 3?__stubs__TEXT?$?__stub_helper__TEXT?L??__cstring__TEXT(&(__eh_frame__TEXTP?P8__DATA__nl_symbol_ptr__DATA__got__DA__la_symbol_ptr__DATA0 H__LINKEDIT ,"? 08 P? 0? 4 ?!p 5 ?! 6 /usr/lib/dyld?@V?5??h?;??j?$ 7 8 9 10*(?< 118 12?/usr/lib/libSystem.B.dylib 13 @/usr/local/lib/gcc/4.9/libgcc_s.1.dylib&?)? UH??H?? ?}?H?u??}?%H?E?H?H??H?H?5?H?Ǹ?N?E??#?E?H?H??H?E?H?H?H????E??E?;E?|տ? 14UH??H??H??????H???????H?Ǹ???E??}?yH??????H???H???????E?H?Ή????E??}?yH??????H???X?}?u??E??????yA?0?E?Hc?H??????H?ƿ?}H??yH??????H????H??????H?????UH??H??H?}?H?}H?H?U?H?5?H?Ǹ????%Z?%\?%^?%`?%?????h?????h(?????h4????h@????%s: file name not given 15cant open %szRx 16?L????????? ?,????????x? 17??????????8? 18"V@___stderrpQr?@dyld_stub_binder???????????r@_close?r @_exit?r(@_fprintf?r0@_open?r8@_read?r@@_write?__mh_execute_header!main%??x?? 19)4;AJPV] 20 21@ 22 _do_cat_die__mh_execute_header_main___stderrp_close_exit_fprintf_open_read_writedyld_stub_binder#include <stdio.h> 23#include <stdlib.h> 24#include <unistd.h> 25#include <sys/types.h> 26#include <sys/stat.h> 27#include <fcntl.h> 28 29static void do_cat(const char *path); 30static void die(const char *s); 31 32int main(int argc, char *argv[]){ 33 int i; 34 35 if (argc < 2) { 36 fprintf(stderr, "%s: file name not given\n", argv[0]); 37 } 38 for (i=0;i<argc;i++) { 39 do_cat(argv[i]); 40 } 41 exit(0); 42} 43 44#define BUFFER_SIZE 2048 45 46static void do_cat(const char *path) { 47 int fp; 48 char buf[BUFFER_SIZE]; 49 int n; 50 51 fp = open(path, O_RDONLY); 52 if (fp < 0) die(path); 53 for (;;) { 54 n = read(fp, buf, sizeof buf); 55 if (n < 0) die(path); 56 if (n == 0) break; 57 if (write(STDOUT_FILENO, buf, n) < 0) die(path); 58 } 59 if (close(fp) < 0) die(path); 60 61} 62 63static void die(const char *s){ 64 fprintf(stderr, "cant open %s", s); 65 exit(1); 66} 67
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。