I need to write a program which gets 4 arguments, the first one a string represents a binary file divided to bytes, and the second, third, and fourth (x,y,z) are 3 integers where their sum is 8. each byte has x left bits, y bits after them, and finally z bits. each group represent a number.
I need to print these numbers. For example for x=4, y=3, z=1 and file has 3 bytes:
1010 0001 1 0101 011 1 0010 001 1 the result would be 10 0 1 5 3 1 2 1 1.
I’d like your help with files in C. This is what I wrote:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
int main(int argc, char** argv) {
if (argc!=5) {
printf("enter a file name and 3 integers such that their sum is 8");
return 0;
} else {
FILE* f;
f=fopen(argv[1], "r");
if (f==NULL) {
printf("File %s does not exists \n", argv[1]);
return 0;
}
else {
int length=0;
int offset=0;
fseek(f, 0, SEEK_END);
length=ftell(f);
fseek(f, 0, SEEK_SET);
while (offset < length) {
int i;
double sum=0;
for (i=1; i<= atoi(argv[2]); ++i) {
double exponent= atoi(argv[1])- i;
sum=getc(f)*pow(2, exponent);
}
printf("%d ", (int)sum);
sum=0;
for (i=1; i<= atoi(argv[3]); ++i) {
double exponent= atoi(argv[1])- i;
sum=fetc(f)*pow(2, exponent);
}
printf("%d ", (int)sum);
sum=0;
for (i=1; i<= atoi(argv[4]); ++i) {
double exponent= atoi(argv[1])- i;
sum=getc(f)*pow(2, exponent);
}
printf("%d ", (int)sum);
offset+=8;
}
fclose(f);
}
}
return 0;
}
Couple of questions:
- I copy the whole
argc, **argvfrom other program which use files. is this Ok? I mean when I entermain c:\stackExchange 5 2 1would it automatically give 4 toargcand an array of the other parameters as strings? I assumed it does, and wrote the above. - I assumed that
getc(f)returns a bit, is this correct?
any other corrections would be gladly welcome.
Regarding your first question,
argcis the number of entries in theargvarray, i.e. the number of arguments plus one. So for your example command lineargcwould be 5, withargvcontaining this:Regarding your second question,
getcreturns an integer, which if it’s notEOFcan be interpreted as a character or a byte depending on if you read text or binary data.