Question

In C. I want to read in the data of a text file into an array...

In C. I want to read in the data of a text file into an array of dynamically allocated structs. The file is read as a command-line argument

The text file format is:

<number of classes in this file>

<department name of class 1>:<number of class 1>:<location of class 1>

<department name of class 2>:<number of class 2>:<location of class 2>

...

Assume that no piece of information in the file contains a colon: the colons are only used as separators. Also, assume that there will be no more than 64 classes in the file.

Here is the struct definition you must use to store each class.

#define MAX_DEPARTMENT_LENGTH 8

#define MAX_COURSE_NUMBER_LENGTH 8

#define MAX_COURSE_LOCATION_LENGTH 32

typedef struct class_info {

       char department [MAX_DEPARTMENT_LENGTH];

       char number [MAX_COURSE_NUMBER_LENGTH];

       char location [MAX_COURSE_LOCATION_LENGTH];

} class_info_t;

Again, this is to be done in C and a response as soon as possible would be preferred, Thank You.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The source code is given below:

/*******
readfile.c
*********/

/* header files*/
#include<stdio.h>
#include<stdlib.h>

/* define constants */
#define MAX_DEPARTMENT_LENGTH 8
#define MAX_COURSE_NUMBER_LENGTH 8
#define MAX_COURSE_LOCATION_LENGTH 32
/* structure declaration */
typedef struct class_info {
char department [MAX_DEPARTMENT_LENGTH];
char number [MAX_COURSE_NUMBER_LENGTH];
char location [MAX_COURSE_LOCATION_LENGTH];
} class_info_t;
/* main function */

int main(int argc,char * argv[]) /* argc - to hold count of command line arguments */
{ FILE * fp; /* argv[] - to hold command line arguments. argv[1] holds data file name passed as command line arg*/
class_info_t * ptr; /* pointer to struct type class_info_t declaration */
int i,j,k,n;
char str[80]; /* string buffer to hold string */
if(argc!=2) /* if file name is not passed as command line arguments */
{printf("Please specify input text file name at command line while executing it");
exit(0);
}
else
{ fp=fopen(argv[1],"r"); /* opens file for reading */
fscanf(fp,"%d",&n); /* reads first number from file which is total no of classes */
if(n>64) /* total classes should not be more than 64 */
{
printf("No of classes is more than 64");
exit(0);
}
else if(n<=0) /* total class is not a -ve number or 0 */
{
printf("No of classes can not be -ve or 0");
exit(0);
}
else
{
ptr=(class_info_t *)malloc(sizeof(class_info_t)*n); /* dynamically allocates memory for all the records */
for(i=0;i<n;i++)
{fscanf(fp,"%s",str); /* reads line wise from file */

for(j=0,k=0;str[j]!=':';j++,k++)
ptr[i].department[k]=str[j];/* populates department data */
ptr[i].department[k]='\0';
  
for(++j,k=0;str[j]!=':';j++,k++)
ptr[i].number[k]=str[j];/* populates number data */
ptr[i].number[k]='\0';

for(++j,k=0;str[j]!='\0';j++,k++)
ptr[i].location[k]=str[j]; /* populates location data */
ptr[i].location[k]='\0';   
}
for(i=0;i<n;i++) /* displays all the records */
{
printf("\nDept: %s\t Number:%s\t Location:%s",ptr[i].department,ptr[i].number,ptr[i].location);
}
printf("\n");
}
fclose(fp);/* closes file */
}
return 0;
}

The source code screen shots are also given for indentation reference:

The output screen shot is also given below:

The above output is taken on ubuntu/linux machine.

The data file data.txt contains following data:

5
aaaaa:2334:12ty
bbbbbb:122:5656
ccccc:343:1212
dddd:2234:5343y
eeeee:554:3236

Add a comment
Know the answer?
Add Answer to:
In C. I want to read in the data of a text file into an array...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am writing a program in C++, which requires me to read an input text file...

    I am writing a program in C++, which requires me to read an input text file using command line argument. However, I am using xcode on my Macbook to write C++ program, and use terminal instead of command. How do you use int main(int argc, char** argv[]) to read an input file. My professor requires us not to hard code the text file name like .open("example.txt"); Thank you!

  • I need to complete tSubinfo and tSectionInfo in data.h in order to be able to save...

    I need to complete tSubinfo and tSectionInfo in data.h in order to be able to save the following info: In tSubInfo id : That isthe identifier of the subseccion ( only one character) subBooks: Vectors that tells us the position where books are in the subsection totSubBooks: total quantity of books in the subsection tSectionInfo: section: Estructure of the type section secSubs:Vector with all subsections (type tSubInfo) of the section (max 10 sections) which have one book totSecSubs: total quantity...

  • Write code to read student data from a csv file and add (prepend) that into a...

    Write code to read student data from a csv file and add (prepend) that into a linked list. Assume the code is written in only one file - main.c. You are REQUIRED to write the struct definition for the linked list node. . The input file name is taken from command line argument. . You can write everything except the struct definition in the main function, or can create multiple functions up to you. Following is the sample file data....

  • Main topics: Files Program Specification: For this assignment, you need only write a single-file ...

    C program Main topics: Files Program Specification: For this assignment, you need only write a single-file C program. Your program will: Define the following C structure sample typedef struct int sarray size; the number of elements in this sanple's array floatsarray the sample's array of values sample Each sample holds a variable number of values, all taken together constitute a Sample Point Write a separate function to Read a file of delimited Sample Points into an array of pointers to...

  • A. File I/O using C library functions File I/O in C is achieved using a file...

    A. File I/O using C library functions File I/O in C is achieved using a file pointer to access or modify files. Processing files in C is a four-step process: o Declare a file pointer. o Open the desired file using the pointer. o Read from or write to the file and finally, o Close the file. FILE is a structure defined in <stdio.h>. Files can be opened using the fopen() function. This function takes two arguments, the filename and...

  • C Language Write the code that dynamically allocates an array of struct objects based on a...

    C Language Write the code that dynamically allocates an array of struct objects based on a size entered through the command line arguments, You will use the following struct and enum. typedef enum Color { RED, GREEN, BLUE } Color; typedef struct MyStruct { int value; Color color; } MyStruct; Write the code to do the following: a. Check for one additional command line argument. Only proceed to the rest of the program if it exists and that the value...

  • URGENT. Need help editing some C code. I have done most of the code it just...

    URGENT. Need help editing some C code. I have done most of the code it just needs the following added: takes an input file name from the command line; opens that file if possible; declares a C struct with three variables; these will have data types that correspond to the data types read from the file (i.e. string, int, float); declares an array of C structs (i.e. the same struct type declared in point c); reads a record from the...

  • Objective: Text File I/0 and Regular Expressions Note that both classes below should handle all exceptions...

    Objective: Text File I/0 and Regular Expressions Note that both classes below should handle all exceptions that might be thrown within them. 1. Create a class that does the following: a. Reads the name of a file to create as the first command line argument. (Overwrite any file with the same name). b. Reads an integer value as the second command line argument. C. The program should generate as many random numbers as are specified in the second command line...

  • (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text...

    (Count the occurrences of words in a text file) Rewrite Listing 21.9 to read the text from a text file. The text file is passed as a command-line argument. Words are delimited by white space characters, punctuation marks (, ; . : ?), quotation marks (' "), and parentheses. Count the words in a case-sensitive fashion (e.g., consider Good and good to be the same word). The words must start with a letter. Display the output of words in alphabetical...

  • C Program: Write a program that will read names, ids, dept names, and cgpа of some...

    C Program: Write a program that will read names, ids, dept names, and cgpа of some students from a file and will show the results. Consider that the name of the file is 'input.csv'. It is just a text file where each line holds information of one student. Example format of two lines in the file is as follows: David Smith, 21, Computer Science, 3.98 Jone Smith, 11, Finance, 3.45 Read all information from the file, and print them on...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT