What I'm having trouble with is getting the 8 bit binary number from a
file and making that an argument char* argv[] for my program
You can not do this. The usual declaration of
int main(int argc, char** argv){};
means that these 2 arguments are provided for you by the operating system when your program is run. What you can do is build something like this for your program, let's say a int myArgCount
and char** myArgValues;
but it seems that you do not need that.
If task
is you program, running task 00001111
will put 00001111
into argv[1]
. And set argc
to 2, since argv[0]
is always the complete path of your program.
At first you say that a binary number can be provided in a file, but in the next paragraph you said
what I want is to turn each 8 bit binary number input separated by spaces
If in fact the input file can have a list of 8-bit binary numbers separated by spaces --- and not just one --- you will need do build a list just like the system does for you, alocating memory for the numbers and creating an array of pointers to them, and an int with the count of numbers. It is not complicated.
The code below tests for an argument on the command line and if not present tries to open source.txt
file to get one. May be it helps.
Note the use of scanf()
to read the values from the file. The mask in use "%8[01]"
is very convenient: it accepts just 0 and 1 for a maximum of 8 digits.
#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main(int argc, char** argv)
{
char binary_number[10];
char* mask = "%8[01]"; // for scanf()
const char* FileName = "source.txt";
if (argc < 2)
{ // no number on the command line
fprintf(stderr, "\nNo 8-bit number provided on the command line\n");
FILE* in_file = fopen(FileName, "r");
if (in_file == NULL)
{
fprintf(stderr, "Could not open [%s]\n", FileName);
return -1;
}
int n = fscanf(in_file, mask, binary_number);
printf("\nFrom the file [%s] number is [%s]\n", FileName, binary_number);
fclose(in_file);
}
else
{ // number provided
strncpy(binary_number, argv[1], 9);
fprintf(stderr, "\nFrom the command line: [%s]\n", argv[1]);
};
return(EXIT_SUCCESS);
};
the program shows
From the command line: [101010]
or
No 8-bit number provided on the command line
From the file [source.txt] number is [11110000]