I have a rather simple code attached below where a file name is manually entered into the program and is defined as an array of size 9, which is correct in this example. The name of the file is passed to a function that is not included here for the purpose of brevity. The function will open the file in read in the data as five vector strings and feed them back to the main program where they can be accessed by pointer arithmetic. As I mentioned in this case the program works, but if I change the size of File1 from 9 to 8 it does not work, because the null terminator is not accounted for. In the spirit of making this a safer program I would like the program to recognize a conditions when the size of the string does not include the null terminator and skip the function call and all of its related lines of code. However, when the null terminator is not included the code produces no error, so I am not sure how to use exception handling in this instance. Any thoughts would be appreciated.
#include <vector>
#include <iostream>
#include <fstream>
#include "Read_Columnar_File.h"
int main(int argc, const char * argv[]) {
std::vector<std::string> str3;
std::vector<int> str4;
std::vector<char> str5;
std::vector<int> str6;
unsigned long size_Misc;
float Peak_Misc_Value;
std::vector<float> MISC_DATA; // Reads in Misc. spending data
char File1[9];
strcpy(File1, "Misc.txt");
Read_Five_Columns(File1,MISC_DATA,str3,str4,str5,str6);
str3.clear(); str4.clear(); str5.clear(); str6.clear();
size_Misc = MISC_DATA.size();
auto max_Misc = std::max_element(MISC_DATA.begin(), MISC_DATA.end());
Peak_Misc_Value = *max_Misc;
}
Consider using std::string as the container for your file name. Then File1.c_str() should always be a null terminated string.
If you really want to do what you write in the question looping through the File1 array and checking if each char is '\0' would tell you if the sting is null terminated. I would not recommend using strcpy like that though since it may write out of bounds of your array.