2016-10-11 4 views
-2

基本的に、以下のコードでは、キーボードからファイル名(input.txtとoutput.txt)を読み取ろうとしていますが、「セグメント化エラー」が発生します。また、小文字を大文字に、大文字を小文字に変換します。助言がありますか?私は間違って何をしていますか?キーボードからファイル名を読み取る

#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 
int main() 
{ 

    char c; 
    int charToLowerCase = 0; 
    int charToUpperCase = 0; 
    int countCharacters = 0; 
    FILE *in_file = NULL; 
    FILE *out_file = NULL; 
    char str_in[100]; 
    char str_out[100]; 
    char *s_in = NULL; 
    char *s_out = NULL; 

    gets(str_in); 
    gets(str_out); 

    if (s_in != NULL) 
    in_file = fopen(str_in, "r"); 

    if (s_out != NULL) 
    out_file = fopen(str_out, "w"); 

    c = fgetc(in_file); 
    while (c != EOF) 
    { 
    if (c >= 'A' && c <= 'Z') 
    { 
    fprintf(out_file, "%c", tolower(c)); 
    charToLowerCase++; 
    } 
    else if (c >= 'a' && c <= 'z') 
      { 
      fprintf(out_file, "%c", toupper(c)); 
      charToUpperCase++; 
      }  
    else 
    fprintf(out_file, "%c", c); 

    c = fgetc(in_file); 
    countCharacters++; 
    } 
    fprintf(out_file, "\n"); 
    fprintf(out_file, "Read %d characters in total, %d converted to upper-case, %d to lower-case.\n", countCharacters, charToUpperCase, charToLowerCase); 

    fclose(in_file); 
    fclose(out_file); 
    return 0; 
} 
+0

'c'は' int'でなければなりません。 'isupper()'と 'islower()'を使うこともできます。 – pzaenger

+1

実際にファイルを開いておき、読み書きを試みます。 's_in == NULL'の代わりに' s_in!= NULL'をテストしますが、テストする必要はありません。その時点ではNULLであることをすでに知っています+彼らは 'fopen(str_in、...)'とは何の関係もありません。 –

+1

誰も 'gets()'を使うべきではありません。 'gets(str_in);'を 'fgets(str_in、sizeof str_in、stdin);に変更してください。 – unwind

答えて

0

あなたが欲しいのは

int main() 
{ 
    int c;      //<<< int instead of char 
    int charToLowerCase = 0; 
    int charToUpperCase = 0; 
    int countCharacters = 0; 
    FILE *in_file = NULL; 
    FILE *out_file = NULL; 
    char str_in[100]; 
    char str_out[100]; 

    gets(str_in); 
    gets(str_out); 

    in_file = fopen(str_in, "r"); 
    if (in_file == NULL) 
    { 
    // file could not be opened 
    printf ("Could not open file %s\n", str_in); 
    return 1; 
    } 

    out_file = fopen(str_out, "w"); 
    if (in_file == NULL) 
    { 
    // file could not be opened 
    printf ("Could not open file %s\n", str_out); 
    return 1; 
    } 

    ... 
+0

ありがとう!できます!しかし、私はこの警告を受け取ります:警告: '取得'は廃止されました(/usr/include/stdio.h:638で宣言されています)[-Wdeprecated-declarations] gets(str_out); –

+1

'gets'は廃止予定です。もう使用しないでください。代わりに 'fgets'を使用してください。詳しくは、[こちらを読む](http://stackoverflow.com/questions/30890696/why-gets-is-deprecated)を参照してください。 –

+0

私はfgets(str_in、100、stdin); ..を使用しようとしていますが、 "ファイルを開くことができませんでした"というメッセージが表示されます。 –

0

s_in == NULLs_out == NULLのための適切な取り扱いはありませんが、流れはすべてのケースで続行:

if (s_in != NULL) 
    in_file = fopen(str_in, "r"); 

if (s_out != NULL) 
    out_file = fopen(str_out, "w"); 

クラッシュが次の行に私のテストで発生します。

c = fgetc(in_file); 

理由in_file==NULL

関連する問題