You are here:

C++/random access file

Advertisement


Question
Can you show me how to open a file for random access, write a byte value to it, read that byte value back and print it to the screen?

Answer
Hello Greg, thank you for the question.

Good ole file i/o. I prefer the C methods of file reading as opposed to the C++ style file reading, so I will demonstrate that. To open a file you call fopen. To write data you call fwrite, and to read data you call fread. Here is some example code:

// Open the file for writing, the parameter "w" specified writing
FILE *pFile = fopen("NameOfFile.txt", "w");

// Make sure the file opened successfully
if(!pFile)
{
cout << "Error opening file\n";
return;
}

// Write a character to the file (1 byte)
char *data = "q";
// Parameters are: a pointer to the data to be written, the size of the data, the number of items to be written, and the file stream pointer
fwrite(data, sizeof(char), 1, pFile);

// Close the file
fclose(pFile);

Now, we need to open the file, parse the data from it and print it to the screen.

// Open the file
FILE *pFile = fopen("NameOfFile.txt", "r");

// Make sure the file was opened
if(!pFile)
{
cout << "Error opening file\n"
return;
}

// Read in the data
char data[32] = {0};
fread(data, sizeof(char), 1, pFile);

// Print the data to the screen
cout << "Data from the file read was: " << data << '\n';

THat should have you pointing in the right direction. If you need more help, or if I failed to specify something properly please do not hesistate to ask me another question.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.