Skip to main content

Section 6.8 File Names and C-Strings

In modern versions of C++, you can use the <string> library for filenames, but earlier versions of C++ required the use of C-strings. The program above will try to open the file called “rawdata.txt” and output its results to a file called “neat.dat” every time it runs, which is not very flexible. Ideally, the user should be able to enter filenames that the program will use instead of the same names. We have previously talked about the char data type that allows users to store and manipulate a single character at a time. A sequence of characters such as “myFileName.dat” can be stored in an array of chars called a c-string, which can be declared as follows:
// Syntax: char C-string_name[LEN];
// Example:
char filename[16];
This declaration creates a variable called filename that can hold a string of length up to 16-1 characters. The square brackets after the variable name indicate to the compiler the maximum number of character storage that is needed for the variable. A \0 or NULL character terminates the C-string, without the system knowing how much of the array is actually used.
Warnings:
  1. The number of characters for a c-string must be one greater than the number of actual characters!
  2. Also, LEN must be an integer number or a declared const int, it cannot be a variable.
C-strings are an older type of string that was inherited from the C language, and people frequently refer to both types as “strings”, which can be confusing.
Typically, string from the <string> library should be used in all other cases when not working with file names or when a modern version of C++ can be used.
You have attempted 1 of 1 activities on this page.