I am stuck on this program that I am supposed to create.

It has to ask the user for a text file where the format looks like:

MATH
101
GEOLOGY
101
GYM
101

Then i'm supposed to store the information from the file in an array which then gets pointed to a function that creates a new data structure and then gets pointed to another function which prints the data from the text file.

I am extremely stuck on this...can anyone please help?

Here is the code i've worked on so far...

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

//created a data structure that consists of a courseName and courseNumber
typedef struct 
{
    
    char courseName;
    int courseNumber;

} Course;

//this is a function that returns a reference to a new course structure allocated from heap
Course *createCourse(int name, int number)
{
    Course *newCourse;
    
    newCourse = (Course *)malloc(sizeof(Course));
    newCourse.courseName = name
    newCourse.courseNumber = number
     
    return newCourse;
}

//this function takes in the array of courseName pointers and courseNumber po
void printCourse(Course *newCourse)
{
    
    printf ("Course Name: %s", (newCourse*).courseName);
    printf ("Course Number: %d", (newCourse*).courseNumber);
        
}  
    
int main()
{
    FILE* pFile = NULL;
    char data[255];
    char filename[80];

  
  // asking the user to enter a filename, the file will read the conents
    printf("Please enter a filename for input: ");
    scanf("%s", &filename); 
  
    pFile = fopen(filename, "r");
    if (pFile == NULL)
    {
        printf ("Error opening file!\n");
        return -1;
    }
 
    while (!feof(pFile))
    {
        fscanf(pFile, "%s \n", data);
        *createCourse(data
        
    
    }
  
    fclose(pFile);
}

Would fgets work best for reading a text file line by line?

MATH
101
GEOLOGY
101
GYM
101

I was looking at some examples and I found this:

while(fgets(data,2,pFile) != NULL)

Would this reach the end of each line or just the end of the text file?

The number 2 means that fgets will just read 2 chars from each line. You want to change that number to an appropriate size.

I've decided to stick with fscanf...i'm still having problems with loops.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.