2

私は現在、3つの引数、2つのファイル(1つの入力と1つの出力)、およびint(出力行の最大長、xと呼ぶ)を取るacプログラムを書いています。入力ファイルのすべての行を読み取り、最初の x 文字を出力ファイルに書き込みたい (効果的にファイルを「トリミング」)。

これが私のコードです:

int main(int argc, char *argv[]) {

  const char endOfLine = '\n';

  if (argc < 4) {
    printf("Program takes 4 params\n");
    exit(1);
  } else {
    // Convert character argument [3] (line length) to an int
    int maxLen = atoi(argv[3]);

    char str[maxLen];
    char *inputName;
    char *outputName;

    inputName = argv[1];
    outputName = argv[2];

    // Open files to be read and written to
    FILE *inFile = fopen(inputName, "r");
    FILE *outFile = fopen(outputName, "w");

    int count = 0;
    char ch = getc(inFile);
    while (ch != EOF) {
        if (ch == '\n') {
          str[count] = (char)ch;
          printf("Adding %s to output\n", str);
          fputs(str, outFile);
          count = 0;
        } else if (count < maxLen) {
          str[count] = ch;
          printf("Adding %c to str\n", ch);
          count++;
        } else if (count == maxLen) {
          str[count] = '\n';
        }
        ch = getc(inFile);
    }

  }

  return 0;
}

唯一の問題は、最後の文字が一重引用符の場合、UTF-8 以外の文字が出力されることです。

For Whom t
John Donne
No man is 
Entire of 
Each is a 
A part of 
If a clod 
Europe is 
As well as
As well as
Or of thin
Each man��
For I am i
Therefore,
For whom t
4

1 に答える 1

1

最後の char 出力が utf-8 継続バイト10xxxxxxであるかどうかを確認できます。そうであれば、文字が完了するまで出力を続けます。

// bits match 10xxxxxx
int is_utf_continue_byte(int ch){
    return ch & 0x80 && ~ch & 0x40;
}

//...
while (is_utf_continue_byte(ch))
    putchar(ch), ch = getchar();
于 2016-12-09T03:49:31.913 に答える