简体   繁体   中英

Reading a text file into a char array, then into a char linked list

So currently I am working on an assignment, and for a section of it I need to be able to read a .txt file into a linked list of type char . I was already confused trying to do this, so I set out on a different path and decided to try to copy the text from the file into a char array, and then one by one copy the values in the array into the linked list.

So far I have my program compiling and running up to a certain point, before I receive the error Segmentation fault (core dumped) .

The code for reading the file is as follow:

void readFile(list<char> &originList, string fileName){
    ifstream fileInput;
    fileInput.open(fileName.c_str());

    int arraySize = fileInput.gcount();
    char tempHold[arraySize];

    if (!fileInput) {
        cout << "Can't open file: " << fileName << "\n";
    } else {
        string contents((istreambuf_iterator<char>(fileInput)), istreambuf_iterator<char>());
        strcpy (tempHold, contents.c_str());

        for (int x = 0; x < fileInput.gcount(); x++) {
            originList.push_back(tempHold[x]);
        }

   }

   fileInput.close();
}

Also to add some context, using cout I determined that the code stops running, instead presenting the error, at the following point:

strcpy (tempHold, contents.data());

Also, I am not 100% on how exactly they work, only a loose idea to be honest. I mostly sourced the idea from this Stack Overflow question, How to copy a .txt file to a char array in c++ , but got confused somewhere a long the way.

Thanks in advance for any help you can provide.

istream::gcount returns the number of characters extracted by the last unformatted input operation performed on the object. Since you did not read anything from the file, you should get something wrong.

Call, for example, istream.getline(); before calling gcount()

Like my comment to your question says, read each character from the file and add it to the list.

void readFile(list<char> &originList, string fileName) {
    ifstream fileInput(fileName.c_str());

    if (!fileInput) {
        cout << "Can't open file: " << fileName << "\n";
    }

    char c;
    while (fileInput.get(c)) {
        originList.push_back(c);
    }

}

Note: while (fileInput.get(c)) This reads the character and returns the stream. When a stream is used as a bool value it checks to see if the stream is valid. Valid means eof() and bad() are both false . - From a comment to the answer to the question linked below.

My answer was adapted from this other Stack Overflow question: Reading from text file until EOF repeats last line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM