C++/random access file
Expert: Eddie - 10/13/2005
QuestionCan 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?
AnswerHello 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