Opening and reading files

I need help with this assignment but its not opening my joke file of (joke.txt) or punchline (punchline.txt)

For this assignment, you will create a program that reads and prints a joke and its punch line from two different files. The first file contains a joke but not its punch line. The second file has the punch line as its last line, preceded by “garbage.” You can pick the joke and the punchline, but please make sure the joke is not inappropriate or offensive in nature. The main function of your program should open the two files and then call two functions, passing each one the file it needs.

The first function should read and display each line in the file it is passed (the joke file). The second function should display only the last line of the file it is passed (the punch line file). It should find this line by seeking to the end of the file and then backing up to the beginning of the last line. You must create all files for this program. Be sure to include comments throughout your code where appropriate. Make sure that your comments thoroughly explain the stream input/output and what is happening in your program.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  //Charles Blackwell CIS 221 M4
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

void printfirstfile(ifstream &);
void printsecondfile(ifstream &);

int main() {
    ifstream joke;
    ifstream punchline;

    // print the joke
    joke.open("joke.txt", ios::in);
    if (!joke) {
        cout << "Error opening the joke. " << endl;
        return 0;
    }
    cout << "                   Charles Joke       " << endl;
    cout << "______________________________________" << endl;
    printfirstfile(joke);

    // print the punch line
    punchline.open("punchline.txt", ios::in);
    if (!punchline) {
        cout << "Error opening the punchline. " << endl;
        return 0;
    }
    cout << "                  Charles punchline   " << endl;
    cout << "______________________________________" << endl;
    printsecondfile(punchline);

    return 0;
}


void printfirstfile(ifstream& file) {
    char ch;

    file.get(ch);


    while (file) {
        cout << ch;
        file.get(ch);
    }
}




void printsecondfile(ifstream& file) {
    char ch;
    
    file.seekg(-1L, ios::end);
   
    file.get(ch);
    while (ch != '\n') {
        
        file.seekg(-2L, ios::cur);
        
        file.get(ch);
    }
    
    file.get(ch);
    
    while (!file.eof()) {
        cout << ch;
        file.get(ch);
    }
}


Make sure the text file is in the same location as the software or put the entire path. Perhaps it cannot find the file and that is why it will not open
Topic archived. No new replies allowed.