The last chapter explained the standard input and output devices handled by C programming language. This chapter cover how C programmers can create, open, close text or binary files for their data storage.
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No. | Mode & Description |
---|---|
1 | r Opens an existing text file for reading purpose. |
2 | w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. |
3 | a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. |
4 | r+ Opens a text file for both reading and writing. |
5 | w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. |
6 | a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
To close a file, use the fclose( ) function. The prototype of this function is −
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.
Following is the simplest function to write individual characters to a stream −
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ..) function as well to write a string into a file. Filmes e series online. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
Given below is the simplest function to read a single character from a file −
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character 'n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ..) function to read strings from a file, but it stops reading after encountering the first space character.
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
Let's see a little more in detail about what happened here. First, fscanf() read just This because after that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.
There are two functions, that can be used for binary input and output −
Both of these functions should be used to read or write blocks of memories - usually arrays or structures.
What are the options to read/write files in .Net Core?
I am working on my first .Net Core app and looking for File.Read*
/File.Write*
functions (System.IO
from .Net
) alternatives.
Using the System.IO.FileStream and System.IO.StreamReader. You can use System.IO.BinaryReader or System.IO.BinaryWriter as well.
Use:
Reference: https://msdn.microsoft.com/pt-br/library/s2tte0y1(v=vs.110).aspx
The code above will read a big file and write to a new big file. The 'intbuffer' value can be set in multiple of 1024. While both source and target file are open, it reads the big file by bytes and write to the new target file by bytes. It will not go out of memory.
For writing any Text to a file.
For reading a Text from file
For Reference here this is the official microsoft document link.
I can't figure out how to use FileStream to write data to a text file..
Assuming you have the data already:
(taken from msdn docs and modified)
The documentation for FileStream gives an excellent example.In short you create a filestream object, and use the Encoding.UTF8 object (or the encoding you want to use) to convert your plaintext to bytes, in which you can use your filestream.write method.But it would be easier to just use the File class, and File.Append* methods.
EDIT: Example
From MSDN:
Assuming your data is string based, this works well, changed your exception handling as you see fit. Making sure add a using System.IO for TextWriter and StreamWriter references.
using System.IO;
Systems start from just £200!
We help businesses of all shapes and sizes, across multiple sectors, to streamline their document filing and processing. DELIVERING:
1 User
Our customer-focussed document filing systems are developed by our in-house development teams in the UK.
Our staff are experts in helping companies and organisations improve their business processes and have been working in this field for over 30 years.
There are many benefits to moving from a paper-based system to an electronic one. Regardless of the size of your business, we have an EDMS solution that is right for your organisation.
We work with a variety of businesses from small start-ups to large multi-national companies, helping them to improve their business processes, improve departmental communication and improve their document security. Read some of our case studies to find out more.
“When a paper invoice comes in, a barcode is attached, it’s scanned and automatically indexed. When staff are working in either Dream or Proactis, they can then click on the invoice and see it using the built-in File Stream Viewer – everything is seamlessly connected.”
Learn more about how Filestream’s Document Management Software can help and benefit your business
-->The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.
BinaryReader | Reads primitive data types as binary values in a specific encoding. |
BinaryWriter | Writes primitive types in binary to a stream and supports writing strings in a specific encoding. |
BufferedStream | Adds a buffering layer to read and write operations on another stream. This class cannot be inherited. |
Directory | Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. |
DirectoryInfo | Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. |
DirectoryNotFoundException | The exception that is thrown when part of a file or directory cannot be found. |
DriveInfo | Provides access to information on a drive. |
DriveNotFoundException | The exception that is thrown when trying to access a drive or share that is not available. |
EndOfStreamException | The exception that is thrown when reading is attempted past the end of a stream. |
EnumerationOptions | |
ErrorEventArgs | Provides data for the Error event. |
File | Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects. |
FileFormatException | The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed. |
FileInfo | Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. This class cannot be inherited. |
FileLoadException | The exception that is thrown when a managed assembly is found but cannot be loaded. |
FileNotFoundException | The exception that is thrown when an attempt to access a file that does not exist on disk fails. |
FileStream | Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations. |
FileSystemAclExtensions | |
FileSystemEventArgs | Provides data for the directory events: Changed, Created, Deleted. |
FileSystemInfo | Provides the base class for both FileInfo and DirectoryInfo objects. |
FileSystemWatcher | Listens to the file system change notifications and raises events when a directory, or file in a directory, changes. |
InternalBufferOverflowException | The exception thrown when the internal buffer overflows. |
InvalidDataException | The exception that is thrown when a data stream is in an invalid format. |
IODescriptionAttribute | Sets the description visual designers can display when referencing an event, extender, or property. |
IOException | The exception that is thrown when an I/O error occurs. |
MemoryStream | Creates a stream whose backing store is memory. |
Path | Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner. |
PathTooLongException | The exception that is thrown when a path or fully qualified file name is longer than the system-defined maximum length. |
PipeException | Thrown when an error occurs within a named pipe. |
RenamedEventArgs | Provides data for the Renamed event. |
Stream | Provides a generic view of a sequence of bytes. This is an abstract class. |
StreamReader | Implements a TextReader that reads characters from a byte stream in a particular encoding. |
StreamWriter | Implements a TextWriter for writing characters to a stream in a particular encoding. |
StringReader | Implements a TextReader that reads from a string. |
StringWriter | Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder. |
TextReader | Represents a reader that can read a sequential series of characters. |
TextWriter | Represents a writer that can write a sequential series of characters. This class is abstract. |
UnmanagedMemoryAccessor | Provides random access to unmanaged blocks of memory from managed code. |
UnmanagedMemoryStream | Provides access to unmanaged blocks of memory from managed code. |
WindowsRuntimeStorageExtensions | Contains extension methods for the IStorageFile and IStorageFolder interfaces in the Windows Runtime when developing Windows Store apps. |
WindowsRuntimeStreamExtensions | Contains extension methods for converting between streams in the Windows Runtime and managed streams in the .NET for Windows Store apps. |
WaitForChangedResult | Contains information on the change that occurred. |
DriveType | Defines constants for drive types, including CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, and Unknown. |
FileAccess | Defines constants for read, write, or read/write access to a file. |
FileAttributes | Provides attributes for files and directories. |
FileMode | Specifies how the operating system should open a file. |
FileOptions | Represents advanced options for creating a FileStream object. |
FileShare | Contains constants for controlling the kind of access other FileStream objects can have to the same file. |
HandleInheritability | Specifies whether the underlying handle is inheritable by child processes. |
MatchCasing | |
MatchType | |
NotifyFilters | Specifies changes to watch for in a file or folder. |
SearchOption | Specifies whether to search the current directory, or the current directory and all subdirectories. |
SeekOrigin | Specifies the position in a stream to use for seeking. |
WatcherChangeTypes | Changes that might occur to a file or directory. |
ErrorEventHandler | Represents the method that will handle the Error event of a FileSystemWatcher object. |
FileSystemEventHandler | Represents the method that will handle the Changed, Created, or Deleted event of a FileSystemWatcher class. |
RenamedEventHandler | Represents the method that will handle the Renamed event of a FileSystemWatcher class. |