-1

入力したソースから入力した宛先にファイルをコピーします。宛先が入力されてから約 2 秒後にセグメンテーション違反エラーが発生します。出力ファイルが作成されているのでfopen()、動作しています。

オンラインで見たところ、たくさんのc=getc(fp). この質問はもう少し基本的なので、私はfread()andを好みます。fwrite()

コード

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

//void rmnewline(char *string);
void remove_last_newline(char *str);

int main()
{
  char x[3];
  x[0]='y';
  int ch;

  while(x[0]=='y'||x[0]=='Y')
  {
    char source[256], destination[256];
    int *a;

    printf("Enter a source file: ");
    fgets(source, 256, stdin);
    if (source[254] == '\n' && source[255] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
    remove_last_newline(source);

    printf("Enter a destination file: ");
    fgets(destination, 256, stdin);
    if (destination[254] == '\n' && destination[255] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
    remove_last_newline(destination);

    FILE *sp, *dp;

    sp = fopen(source, "r");
    if (sp == NULL) { printf("ERROR: Could not open source file."); exit(1); }
    dp = fopen(destination, "w");
    if (dp == NULL) { printf("ERROR: Could not open destination file."); exit(1); }
    while(1)
    {
      fread(a, 1, 1, sp);
      if (feof(sp))
      break;
      fwrite(a, 1, 1, dp);
    }

    fclose(sp);
    fclose(dp);

    printf("Run Again?(y/n):");
    fgets(x, 2, stdin);
    while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
 }

}

/*void rmnewline(char *string)
{
    int i, l = strlen(string);

    for(i=0; i<=l; i++)
    {
      if(string[i] == '\0')
         return;
      if(string[i] == '\n')
     {
       string[i] == '\0';
       return;
     }
  }

}*/

void remove_last_newline(char *str) {
    if (*str == '\0') return; /* do nothing if the string is empty */
    while(str[1] != '\0') str++; /* search for the end of the string */
    if (*str == '\n') *str = '\0'; /* if the last character is newline, delete it */
}
4

3 に答える 3

2

fgets読み取った改行文字をバッファに格納します。

fopen「指定されたファイル」を開くことができず、fopenを返す場合がありますNULL

改行文字がバッファにある場合は削除してください。
これは、次の関数を使用して実行できます。

void remove_last_newline(char *str) {
    if (*str == '\0') return; /* do nothing if the string is empty */
    while(str[1] != '\0') str++; /* search for the end of the string */
    if (*str == '\n') *str = '\0'; /* if the last character is newline, delete it */
}

ファイル名を読み込んだ後、この関数にsourceandを渡してください。destination

于 2015-10-03T14:46:15.507 に答える
1

の戻り値を確認してくださいfopen
プログラムは SEGFAULT を取得してfread(a, 1, 1, sp); います。これは、SP が NULL の場合に発生します。プログラムは 1 バイトだけを読み取ろうとするため、オーバーフローの可能性はありません。

fopenソースが最後に改行文字で構成されているため、失敗します。newlinefopen を呼び出す前にソースと宛先から文字を削除すると、プログラムは正常に動作します。

于 2015-10-03T15:06:12.513 に答える
0

主な問題は、'\n'ファイル名に. 他の2つの回答はそれをよく答えており、少なくとも1つは受け入れられるに値します。fopen()fopen()

その後のOP編集は、新しい障害int a[1]を引き起こすように変更されました。int *aへの変更を提案

char a[1];
于 2015-10-03T16:17:31.377 に答える