wc
私は現在Cでコマンドライン呼び出しのレプリカを作成しています。 [tst.txt]ファイル
とそのファイルを読み取るCコードがあります。コマンドは、2 つの改行文字 ('\n') を表すwc tst.txt
出力で応答します。2 6 20 tst.txt
しかし、私のコードには3つの改行があります。私はこれが原因だと思います。体系的なファイルの末尾に新しい行が追加されます(3行目の後)。
このコマンドが末尾の改行(EOFの末尾を意味する)を削除すると思うのは正しいですか?wc
それとも私のコードが間違っていますか?
ユニットをもう1つ追加したのではないでしょうか?
これは私のコードです。
#include <stdio.h>
#include <string.h>
int checkForNewLine(char* line, int lineSize);
int main(int argc, char **argv) {
// declare variables
FILE *inputFile; // pointer to inputted file
inputFile = fopen(argv[1], "r"); // set input file to 2nd cmd-line arg.
int newLineCount = 0;
int newLineIncr = 0;
// if file is not found
if (inputFile == NULL){
printf("%s", "File not found\n");
return (-1); // end program
}
char line[201]; // set line to 200 char MAX.
while (fgets(line, 201, inputFile) != NULL){
// new line count
newLineCount = newLineCount + checkForNewLine(line, 201);
}
if (feof(inputFile)) {
}
else {
printf("%s", "Some Other Error...");
}
printf("New Line Count [%d]\n", (newLineCount));
fclose(inputFile);
}
int checkForNewLine(char *line, int lineSize){
int count = 0;
for (int i = 0; i < lineSize; i++) {
if (line[i] == '\0'){
count++;
printf("count amount: %d\n", count);
break;
}
}
return count;
}
ベストアンサー1
~からman 3 fgets
:
The fgets() function shall read bytes from stream into the array
pointed to by s, until n−1 bytes are read, or a <newline> is read and
transferred to s, or an end-of-file condition is encountered.
したがって、コードは最後の行を計算します。末尾に改行文字があるかどうかに関係なく(そうではありません)EOFが発生したためです。結局、checkForNewLine()
関数は改行文字ではなくヌル文字をチェックしています。などod
を使用して、hexdump
入力ファイルの最後の文字が何であるかを確認してください。