OP is mixing fgets()
with binary reads of a file.
fgets()
reads a file up to the buffer size provided or reaching a \n
byte. It is intended for text processing. The typical way to determine how much data was read via fgets()
is to look for a final \n
- which may or may not be there. The data read could have embedded NUL bytes in it so it becomes problematic to know when to stop scanning the buffer. on a NUL byte or a \n
.
Fortunately this can all be dispensed with, including the file seek and buffers.
// "rb" should be used when looking at a file in binary. C11 7.21.5.3 3
FILE *f = fopen(argv[1], "rb");
b = atoi(argv[2]);
unsigned long byteCount = 0;
int ch;
while ((ch = fgetc(f)) != EOF) {
if (ch == b) {
byteCount++;
}
}
The OP error checking is good. But the for(k = 0; k < sizeof(buffer); k++){
loop and its contents had various issues. OP had if(b = newFile[i]){
which should have been if(b == newFile[i]){