I'm trying to create a simple C program that reads lines of string from a file then output it to the terminal, but apparently it keeps crashing and I don't know where I went wrong...I suspect that it might be the way that I'm handling the arrays in my code, because I'm still very new to C, so I'm still getting used to the ways that arrays are used and declared..
This is what my code currently looks like:
typedef struct my_string
{
char str[256]; // my string contains an array of 255 characters + null
} my_string;
//Output lines from the file into terminal
void print(int count, my_string a[20]) {
for (int i = 0; i < count; i++)
{
printf("%s\n", a[i]);
}
}
//Read lines from file
void read(FILE *file_ptr) {
int i;
int numberOfLines;
my_string lineArray[20];
fscanf(file_ptr, "%d\n", &numberOfLines);
for (i=0; i < numberOfLines; i++) {
fscanf(file_ptr, "%[^\n]\n", lineArray[i].str);
}
print(numberOfLines, lineArray);
}
void main()
{
FILE *file_ptr;
// open the file and read from it
if ((file_ptr = fopen("mytestfile.dat", "r")) == NULL)
printf("File could not be opened");
else {
read(file_ptr);
}
fclose(file_ptr);
}
The text file that I'm trying to read from is this:
10
Fred
Eric
James
Jaiden
Mike
Jake
Jackson
Monica
Luke
Kai
Thanks