C 写入文件失败

C failed to write to file

我确实写了一个函数“write_n”,它将源文件的每第 n 行写入目标文件。我确实希望,没有一行超过 80 个字符,我的 n 大于或等于 0,小于或等于 100。

int write_n(const char *src_path, const char *dst_path, int n){
    
    int i = 0;
    char buffer[100];

    if(n >= 101 || n <= 0) return -1; // ERROR -1 -> n is not between 0 and 100!

    FILE *src = fopen(src_path, "r");
    if(src == NULL) return -10; // ERROR -10 -> failed to open source file!

    FILE *dst = fopen(dst_path, "w");
    if(dst == NULL) return -11; // ERROR -11 -> failed to open destination file!

    while (fgets(buffer, 80, src) != NULL){
        i++;
        if(n == i){
            fprintf(dst, "%s", buffer); 
            i = 0;
        }
    }
    
    fclose(dst);
    fclose(src);
    
    return 0;
}

我确实有一些测试用例,但以下测试用例失败了:

 Error: Unexpected result for function 'write_n'! In total 1 test case failed:

'write_n':
==========
n: 2
Content of input file:
1: This is a text file that contains two lines. Each line is 80 characters wide
2: This is the second line of text file. It is also is 80 characters wide!!!!!!
3: This is the third line of text file. It is also is 80 characters wide!!!!!!!
4: This is the fourth line of text file. It is also is 80 characters wide!!!!!!
5: This is the fifth line of text file. It is also is 80 characters wide!!!!!!!
6: This is the sixth line of text file. It is also is 80 characters wide!!!!!!!

Expected content of output file:
2: This is the second line of text file. It is also is 80 characters wide!!!!!!
4: This is the fourth line of text file. It is also is 80 characters wide!!!!!!
6: This is the sixth line of text file. It is also is 80 characters wide!!!!!!!
Actual content of output file:

我似乎不明白为什么这个测试用例会失败。在一行中使用单个字符一切正常。

将缓冲区大小增加到 81,以存储终止字符(零)。

C 中的每个字符串末尾都必须有终止空字符 - 搜索“C 字符串”以获取更多信息。