Laboratory-Tasks/Exercise 3 - Virtual Initialization (Week 4)/ex3.c

97 lines
2.3 KiB
C
Raw Normal View History

/* License: AGPLv3 or later. https://www.gnu.org/licenses/licenses.html
*
* Exercise 3 - Virtual Initialization (Week 4)
* Name: Manish
* Student Login: *****
*
* Compile as:
* $ gcc -std=c11 -Wall -o ex3 ex3.c
*
* Assumption: Where input is 0 indexed and not starting from 1
*/
#include <stdio.h>
#include <stdlib.h>
int data[100];
int forward[100];
int backward[100];
int valid_indexes = -1;
int main(void)
{
printf("Enter file name: ");
char filename[257];
// Assuming filename/file path won't be longer than 256 characters
scanf("%256s", filename);
FILE* file = fopen(filename, "r");
if (!file)
{
perror(filename);
exit(EXIT_FAILURE);
}
int what = -10;
int where = -10;
// Trailing whitespaces to consume all subsequent ' ', \t, \n, \r
/* NOTE: Not using file position checks to detect when stuck in a loop
* assuming input to be in exact format as specified
*/
while (fscanf(file, " %d ", &what) != EOF
&& fscanf(file, " %d ", &where) !=EOF)
{
if (what == -1 && where == -1)
{
break;
}
// Where/index cannot be less than 0
if (where < 0 || where >= 100)
{
fprintf(
stderr,
"Where index is %d but arrays index is only up to 99. "
"Ignoring this input.\n",
where);
continue;
}
data[where] = what;
forward[++valid_indexes] = where;
backward[where] = valid_indexes;
}
int probe;
// Trailing whitespace to consume all subsequent ' ', \t, \n, \r
while(fscanf(file, " %d ", &probe) != EOF)
{
if (probe == -1)
{
break;
}
// Probe/index cannot be less than 0
if (probe < 0 || probe >= 100)
{
printf("Position %d does not exist.\n",probe);
continue;
}
if (backward[probe] <= valid_indexes
&& forward[backward[probe]] == probe)
{
printf(
"Position %d has been initialized to value %d.\n",
probe,
data[probe]
);
}
else
{
printf("Position %d has not been initialized.\n", probe);
}
}
fclose(file);
return 0;
}