Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3963458
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T03:13:03+00:00 2026-05-20T03:13:03+00:00

For a class I have to write a program to read in a text

  • 0

For a class I have to write a program to read in a text file in the format of:


T A E D Q Q
Z H P N I U
C K E W D I
V U X O F C
B P I R G K
N R T B R B
EXIT
THE
QUICK
BROWN
FOX


I’m trying to get the characters into an array of chars, each line being its own array.
I’m able to read from the file okay, and this is the code I use to parse the file:


char** getLinesInFile(char *filepath)  
{  
    FILE *file;  
    const char mode = 'r';  
    file = fopen(filepath, &mode);  
    char **textInFile;  

    /* Reads the number of lines in the file. */
    int numLines = 0;
    char charRead = fgetc(file);
    while (charRead != EOF)
    {
        if(charRead == '\n' || charRead == '\r')
        {
            numLines++;
        }
        charRead = fgetc(file);
    }

    fseek(file, 0L, SEEK_SET);
    textInFile = (char**) malloc(sizeof(char*) * numLines);

    /* Sizes the array of text lines. */
    int line = 0;
    int numChars = 1;
    charRead = fgetc(file);
    while (charRead != EOF)
    {
        if(charRead == '\n' || charRead == '\r')
        {
            textInFile[line] = (char*) malloc(sizeof(char) * numChars);
            line++;
            numChars = 0;
        }
        else if(charRead != ' ')
        {
            numChars++;
        }
        charRead = fgetc(file);
    }

    /* Fill the array with the characters */
    fseek(file, 0L, SEEK_SET);
    charRead = fgetc(file);
    line = 0;
    int charNumber = 0;
    while (charRead != EOF)
    {
        if(charRead == '\n' || charRead == '\r')
        {
            line++;
            charNumber = 0;
        }
        else if(charRead != ' ')
        {
            textInFile[line][charNumber] = charRead;
            charNumber++;
        }
        charRead = fgetc(file);
    }

    return textInFile;
}

This is a run of my program:


Welcome to Word search!

Enter the file you would like us to parse:testFile.txt
TAEDQQ!ZHPNIU!CKEWDI!VUXOFC!BPIRGK!NRTBRB!EXIT!THE!QUICK!BROWN!FOX
Segmentation fault


What’s going on? A), why are the exclamation marks there, and B) why do I get a seg fault at the end? The last thing I do in the main is iterate through the array/pointers.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T03:13:04+00:00Added an answer on May 20, 2026 at 3:13 am

    1) In the first part of your program, you are miscounting the number of lines in the file. The actual number of lines in the file is 11, but your program gets 10. You need to start counting from 1, as there will always be at least one line in the file. So change

    int numLines = 0;
    

    to

    int numLines = 1;
    

    2) In the second part of the program you are miscounting the number of characters on each line. You need to keep your counter initializations the same. At the start of the segment you initialize numChars to 1. In that case you need to reset your counter to 1 after each iteration, so change:

    numChars = 0;
    

    to

    numChars = 1;
    

    This should provide enough space for all the non-space characters and for the ending NULL terminator. Keep in mind that in C char* strings are always NULL terminated.

    3) Your program also does not account for differences in line termination, but under my test environment that is not a problem — fgetc returns only one character for the line terminator, even though the file is saved with \r\n terminators.

    4) In the second part of your program, you are also not allocating memory for the very last line. This causes your segfault in the third part of your program when you try to access the unallocated space.

    Note how your code only saves lines if they end in \r or \n. Guess what, EOF which technically is the line ending for the last line does not qualify. So your second loop does not save the last line into the array.

    To fix this, add this after the second part:
    textInFile[line] = (char*) malloc(sizeof(char) * numChars);

    4) In your program output you are seeing those weird exclamation points because you are not NULL terminating your strings. So you need to add the line marked as NULL termination below:

    if(charRead == '\n' || charRead == '\r')
    {
        textInFile[line][charNumber] = 0; // NULL termination
        line++;
        charNumber = 0;
    }
    

    5) Because you are checking for EOF, you have the same problem in your third loop, so you must add this before the return

    textInFile[line][charNumber] = 0; // NULL termination
    

    6) I am also getting some headaches because of the whole program structure. You read the same file character by character 3 times! This is extremely slow and inefficient.

    Fixed code follows below:

    char** getLinesInFile(char *filepath)  
    {  
        FILE *file;  
        const char mode = 'r';  
        file = fopen(filepath, &mode);  
        char **textInFile;
    
        /* Reads the number of lines in the file. */
        int numLines = 1;
        char charRead = fgetc(file);
        while (charRead != EOF)
        {
            if(charRead == '\n' || charRead == '\r')
            {
                numLines++;
            }
            charRead = fgetc(file);
        }
    
        fseek(file, 0L, SEEK_SET);
        textInFile = (char**) malloc(sizeof(char*) * numLines);
    
        /* Sizes the array of text lines. */
        int line = 0;
        int numChars = 1;
        charRead = fgetc(file);
        while (charRead != EOF)
        {
            if(charRead == '\n' || charRead == '\r')
            {
                textInFile[line] = (char*) malloc(sizeof(char) * numChars);
                line++;
                numChars = 1;
            }
            else if(charRead != ' ')
            {
                numChars++;
            }
            charRead = fgetc(file);
        }
    textInFile[line] = (char*) malloc(sizeof(char) * numChars);
    
        /* Fill the array with the characters */
        fseek(file, 0L, SEEK_SET);
        charRead = fgetc(file);
        line = 0;
        int charNumber = 0;
        while (charRead != EOF)
        {
            if(charRead == '\n' || charRead == '\r')
            {
                textInFile[line][charNumber] = 0; // NULL termination
                line++;
                charNumber = 0;
            }
            else if(charRead != ' ')
            {
                textInFile[line][charNumber] = charRead;
                charNumber++;
            }
            charRead = fgetc(file);
        }
        textInFile[line][charNumber] = 0; // NULL termination
    
        return textInFile;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For my programming class I have to write a linked list class. One of
I have class with internal property: internal virtual StateEnum EnrolmentState { get { ..getter
I am trying to create a simple appplication that can read from a text
Can an abstract class have a constructor? If so, how can it be used
Can a class have a Service Contract attribute and its methods Operation Contract. Or
I have class method that returns a list of employees that I can iterate
I have: class MyClass extends MyClass2 implements Serializable { //... } In MyClass2 is
I have class A: public class ClassA<T> Class B derives from A: public class
I have class with a member function that takes a default argument. struct Class
I have class Cab(models.Model): name = models.CharField( max_length=20 ) descr = models.CharField( max_length=2000 )

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.