Hi everyone!
I am currently learning C++, and just learned how to output to a file in binary mode. I wrote a program that prompts the user for a filename then it asks him wether he wants to read or write to the file. The problem is that, even though the code compiles, it never manages to create the file, and I don't know why.
Here's the code for you to check out:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int get_int(int default_value);
char name[20];
int age;
int main()
{
char filename[81];
int n;
int menu; // Integer used to select a menu command.
int recsize = sizeof(name) + sizeof(int);
cout << "Enter file name: ";
cin.getline(filename, 80);
// Open file for binary read-write access.
fstream fbin(filename, ios::in | ios::out | ios::binary);
if (!fbin)
{
cout << "Could not open file " << filename << endl;
return -1;
}
while(1)
{
// Prompt for a command and then get a menu number
cout << "Enter a choice: 1. Write Record, 2. Read Record, 3. Exit. ";
menu = get_int(3);
if (menu == 1)
{ // Menu choice #1. Write
cout << "Enter a record number: "; // Get record #
n = get_int(0);
fbin.seekp(n * recsize);
cout << "Enter name: "; // Get data to write
cin.getline(name, 19);
cout << "Enter age: ";
age = get_int(0);
// Write data to the file.
fbin.write(name, 20); // Write to file
fbin.write(reinterpret_cast<char*>(&age), sizeof(int));
}
else if (menu == 2)
{ // Menu choice #2. Read
cout << "Enter a record number: "; // Get record #
n = get_int(0);
fbin.seekp(n * recsize);
// Read data from the file.
fbin.read(name, 20); // Read data from file
fbin.read(reinterpret_cast<char*>(&age), sizeof(int));
// Display the data and close.
cout << "The name is: " << name << endl; // Display the data
cout << "The age is: " << age << endl;
}
else // Other menu choices: Exit.
break;
}
fbin.close();
return 0;
}
// Get integer function
// Get an integer from keyboard; return default
// value if user enters 0-length string.
int get_int(int default_value)
{
char s[81];
cin.getline(s, 80);
if (strlen(s) == 0)
return default_value;
return atoi(s);
}
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.