Reputation: 177
I did write a function "write_n", that writes every nth line of a source file to a destination file. I do expect, that no line is longer than 80 characters and my n is greater or euqal to 0 and lower or euqal to 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;
}
I do have some test cases and the following test case failed:
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:
I don't seem to get it why this test case is failing. With single characters in a line everything works just fine.
Upvotes: 1
Views: 172
Reputation: 5389
Increase your buffer size to 81, to store terminating character (zero).
Every string in C must has terminating null character at the end - search “C strings” for more information.
Upvotes: 2