高校生です。現在cの勉強をしています。
やりたいこと
・コマンドライン引数からファイル名を受け取りそのファイルのデータを読み込む
・読み取ったデータを別のファイルに書き込む
・output.txtの1行目に"English Conversation!"を書き込む。
補足
・読み込むファイル名は"input.txt"
txt
1//ここ(1行目は空白) 2Hello! 3How've you been? 4It's so good to see you. 5It's good to see you. 6How've you been? 7Just fine. 8
・書き込むファイル名は"output.txt"
txt
1//空
読み込み・書き込みはそれぞれfgets,fputsを用いる。
現在、自分でかけたコードは以下です。
c
1#include<stdio.h> 2#include<stdlib.h> 3#define NUM 256 4 5 6int main(int argc,char*argv[]){ 7 FILE *fp1; 8 FILE *fp2; 9 char str[NUM]; 10 char*filename_in=argv[1]; 11 char*filename_out=argv[2]; 12 fp1=fopen(filename_in,fp1); 13 fp2=fopen(filename_out,fp2); 14 if(fp1==NULL||fp2==NULL){ 15 if(fp1==NULL){ 16 printf("Cannot Open Read File\n"); 17 } 18 else{ 19 printf("Cannot Open Write File\n"); 20 } 21 exit(1); 22 } 23 fputs("English Conversation!",fp2); 24 while(fgets(str,NUM,fp1)!=NULL){ 25 fputs(str,fp2); 26 }; 27 fclose(fp1); 28 fclose(fp2); 29 return 0; 30 } 31 32
コンパイル結果
c
1 2$ cc 5-1.c -o test5 35-1.c:11:24: warning: incompatible pointer types passing 'FILE *' 4 (aka 'struct __sFILE *') to parameter of type 'const char *' 5 [-Wincompatible-pointer-types] 6 fp1=fopen(filename_in,fp1); 7 ^~~ 8/usr/include/stdio.h:245:61: note: passing argument to parameter here 9FILE *fopen(const char * __restrict, const char * __restrict); 10 ^ 115-1.c:12:25: warning: incompatible pointer types passing 'FILE *' 12 (aka 'struct __sFILE *') to parameter of type 'const char *' 13 [-Wincompatible-pointer-types] 14 fp2=fopen(filename_out,fp2); 15 ^~~ 16/usr/include/stdio.h:245:61: note: passing argument to parameter here 17FILE *fopen(const char * __restrict, const char * __restrict); 18 ^ 192 warnings generated. 20
実行結果```c
$ ./test5 input.txt output.txt
zsh: segmentation fault (core dumped) ./test5 input.txt output.txt
まずコンパイルにおいて何がまずかったのでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/27 00:08
2018/05/27 00:27