Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ filebuf Class

❮ fstream classes


Example

Use a filebuf object to create a file:

#include <iostream>
#include <fstream>
using namespace std;

int main() {

  // Create a file
  filebuf MyFileBuf;
  MyFileBuf.open("filename.txt", ios_base::out);
  
  // Write into the file
  MyFileBuf.sputn("Hello World!", 12);
  
  // Close the file
  MyFileBuf.close();
} 

Definition and Usage

The filebuf class is used to read and write files. There is a filebuf object used internally by the fstream, ifstream and ofstream classes.

The filebuf class is defined in the <fstream> header file.


File Handling Functions

File handling functions open and close files.

open()

The open(filepath, mode) method opens the file at the path specified by filepath. If a file is already open then this method has no effect. The mode parameter is a set of flags that indicate the way in which the file will be used. The following flags can be used in the mode parameter:

  • ios_base::in - The file is open for reading.
  • ios_base::out - The file is open for writing.
  • ios_base::binary - File contents are treated as binary data instead of text.
  • ios_base::ate - The file is opened with the file pointer at the end of the file.
  • ios_base::app - New data is always written to the end of the file.
  • ios_base::trunc - The contents of the file are deleted as soon as the file is opened.

Flags can be combined using the | operator. For example, to open a file for both reading and writing, use ios_base::in|ios_base::out.

filebuf MyFileBuf;
MyFileBuf.open("filename.txt", ios_base::in|ios_base::out);

is_open()

The is_open() method returns a boolean value, true if a file is open and false if there is no file open.

filebuf MyFileBuf;
cout << MyFileBuf.is_open(); << "\n"; // Displays 0 because the file is not open
MyFileBuf.open("filename.txt");
cout << MyFileBuf.is_open(); << "\n"; // Displays 1 because the file is open

close()

The close() method closes a file. It is good to close a file when you are finished working with it to free up resources.

MyFileBuf.close();

File Pointer Functions

File pointers are internal variables which indicate where in the file to read or write.

File pointer functions are used to manipulate file pointers. There is a read file pointer and a write file pointer, but for ordinary files the filebuf class uses the same pointer for both actions, so changing one of them also changes the other one.

pubseekpos()

The pubseekpos(position, pointer) method moves the file pointer to a specified position relative to the start of the file and returns the new position. The pointer property specifies whether to move the read pointer, the write pointer or both by using the following flags:

  • ios_base::in - Move the read pointer.
  • ios_base::out - Move the write pointer.

The | operator can be used to combine both flags like this: ios_base::in|ios_base::out

cout << MyFileBuf.pubseekpos(4, ios_base::in);

pubseekoff()

The pubseekoff(offset, origin, pointer) moves the file pointer to a specified position given by an offset relative to a specified origin and returns the new position.

The origin parameter must be one of the following values:

  • ios_base::beg - Offset relative to the beginning of the file.
  • ios_base::cur - Offset relative to the currend file pointer position.
  • ios_base::end - Offset relative to the end of the file.

The pointer property specifies whether to move the read pointer, the write pointer or both by using the following flags:

  • ios_base::in - Move the read pointer.
  • ios_base::out - Move the write pointer.

The | operator can be used to combine both flags like this: ios_base::in|ios_base::out

cout << MyFileBuf.pubseekoff(-5, ios_base::end, ios_base::in);

File Reading Functions

in_avail()

The in_avail() method returns the number of characters available to be read in the file.

cout << MyFileBuf.in_avail();

snextc()

The snextc() method moves the file pointer foward by one character and returns the ASCII value of the character at the new position.

cout << MyFileBuf.snextc();

sbumpc()

The sbumpc() method returns the ASCII value of the character at the current position and moves the file pointer foward by one character.

cout << MyFileBuf.sbumpc();

sgetc()

The sgetc() method returns the ASCII value of the character at the current position without moving the file pointer.

cout << MyFileBuf.sgetc();

sgetn()

The sgetn(destination, n) method reads n characters from the file and writes them into the char array specified by the destination parameter. This method returns the number of characters which were read.

char destination[20];
int amount = MyFileBuf.sgetn(destination, 19);
destination[amount] = '\0'; // Add a null terminating character to the string
cout << destination;

File Writing Functions

sputc()

The sputc() method writes a character at the current position and then moves the file pointer forward by one character. This method returns the ASCII value of the character that was written.

cout << MyFileBuf.sputc();

sputn()

The sputn(source, n) method writes n characters from the char array specified by the source parameter into the file. The file pointer is moved forward by n characters. This method returns the number of characters that were written to the file.

char source[] = "Hello World!";
int num = MyFileBuf.sputn(source, 12);
cout << num << " characters were written to the file";

❮ fstream classes

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.