I have a very simple problem. I need to read in the contents of a file into a char array in C. The file will always be formatted as two columns of letters, e.g.:
A B
B C
E X
C D
Each letter represents a vertex on a graph, which I'll be dealing with later. I've learned programming using C++ and Java, but I'm not extraordinarily familiar with C specifically.
What's causing the problem that I can't figure out is the fact that the file is multiple lines long. I need each letter to occupy a slot in the array, so in this case it'd be:
array[0] = 'A', array[1] = 'B', array[2] = 'B', array[3] = 'C'
and so on.
Eventually I'll need the array to not include duplicates, but I can handle that later. I wrote a program earlier this semester that read in a single line of ints from a file and it worked fine, so I copied most of that code, but it's not working in this case. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int i;
int count = 0;
char * vertexArray;
char ch = '\0';
// open file
FILE *file = fopen( argv[1], "r" );
// count number of lines in file
while ((ch=fgetc(file)) != EOF)
if(ch == '\n') count++;
// numbers of vertices is twice the number of lines
int size = count*2;
// declare vertex array
vertexArray = (char*) calloc(size, sizeof(char));
// read in the file to the array
for(i=0; i<size; i++)
fscanf(file, "%c", &vertexArray[i]);
// print the array
for(i=0; i<size; i++)
printf("%c\n", vertexArray[i]);
fclose( file );
}
I know I need to be testing for the file opening and being read properly and whatnot, but I'll add that in later. Just trying to read in the array for now. My output in this case is 8 blank lines. Any help would be great!