I’m trying to understand some differences in file i/o techniques. Suppose I have the following code:
FILE *work_fp;
char record[500] = {0};
while(!feof(work_fp))
{
static int first = 1;
fgets(record, 200, work_fp);
if (first)
{
var1 = 2;
length += var1;
}
first = 0;
if (feof(work_fp))
{
continue;
}
if((int)strlen(record) < length)
{
fclose(work_fp);
std::ostringstream err;
err << "ERROR -> Found a record with fewer bytes than required in file."
<< std::endl;
throw std::runtime_error(err.str());
}
const int var2 = 1;
if(memcmp(argv[1], record + var2, 3) == 0)
{
load_count_struct(record, var1);
}
}
I’m not seeing how the second if argument can be true.
if (feof(work_fp))
{
continue;
}
If feof(work_fp) is true wouldn’t the while argument be false? Then the continue could never get called?
FOLLOW UP QUESTION:
Ok, I see how fgets can cause work_fp to reach eof conditions.
Suppose I want to try and implement this another way. Using getline(), for example.
std::string data(file);
std::ifstream in(data.c_str());
if (!in.is_open())
{
std::ostringstream err;
err << "Cannot open file: " << file << std::endl;
throw std::runtime_error(err.str());
}
std::string buffer = "";
std::string record = "";
while (getline(in, buffer))
{
static int first = 1;
if (first)
{
var1 = 2;
length += var1;
}
first = 0;
if (//What should go here?!?)
{
break;
}
// etc...
}
Any suggestions? I’m thinking
if (buffer == std::string::npos)
no?
The line:
can advance to read/write head to the end of the file, thus changing the return value on
feof.