Debug Assertion Failed VS2010 - c++

I'm making a very simple program to read in from a text file and print the contents. When the file finishes compiling I keep getting this debug assertion failed message!
I've never seen it before and can't seem to find any solutions.
(It won't let me post an image because my rep isn't high enough!)
The code
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file = fopen("C:\\Users\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");
char c;
do
{
c = fgetc(file);
printf("%c", c);
}
while(c != EOF);
fclose(file);
return 0;
printf("\n\n\n");
system("pause");
}

Step through your code using the debugger to find the line that is causing the debug assertion, and check to see if the file is opened.
In the line
FILE *file = fopen("C:\\Users\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");
it looks like you missed a '\' before 'Kyne' so it should be
FILE *file = fopen("C:\\Users\\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");
There are other issues like calling return 0; before the end of the main block.

I don't see any checks if file was opened properly. Also, I would check for EOF mark before first read - use while and feof() instead. Finally, these lines:
printf("\n\n\n");
system("pause");
will never get called, as you do return 0 after fclose() - move it [return 0] to the end.
Try this:
int main()
{
FILE *file = fopen("C:\\Users\\Kyne\\Desktop\\AdvProgrammingAssignment\\employees.txt", "r");
if(!file)
{
printf("File could not be opened!\n");
return -1;
}
while(!feof(file))
{
char c = fgetc(file);
printf("%c", c);
}
fclose(file);
printf("\n\n\n");
system("pause");
return 0;
}
Most likely, your error originated in using FILE* set to NULL - you have one slash missing after \\Users, so file probably was never opened and fopen() was constantly returning NULL.

Related

C++ remove() and rename() gives "Permission error"

I can't figure out what is happening in my program, it's a simple function to clear all the Windows '\r' from a file, putting all the chars in another file and then rename it to substitute the old file. Every time I execute the function the rename() and remove() functions give me "Permission error" even if I had all the file pointers closed and the file on my PC is closed in every program. Here's the code
static bool correctFile(string fileName) {
string name = fileName;
FILE* test = fopen(fileName.c_str(), "rb");
FILE *in, *out;
char stringTest[1000];
bool isWinFile = false;
if (!test) {
return false;
}
fread(stringTest, 1, 1000, test);
fclose(test);
for (size_t i = 0; i < strlen(stringTest) && !isWinFile; i++) {
if (stringTest[i] == '\r') {
isWinFile = true;
}
}
if (isWinFile) {
in = fopen(fileName.c_str(), "rb");
string tempFile = name + ".temp";
out = fopen(tempFile.c_str(), "wb");
if (!in || !out) {
return false;
}
char temp;
while (fread(&temp, sizeof(temp), 1, in) > 0) {
if (temp != '\r') {
fwrite(&temp, sizeof(temp), 1, out);
}
}
fclose(in);
fclose(out);
if (std::remove(fileName.c_str())) {
std::cerr << "Error: " << strerror(errno);
return false;
}
if (std::rename(tempFile.c_str(), fileName.c_str())) {
return false;
}
}
return true;
}
If you find an error in this please tell me, thanks
I found out that the old file and the new file must not be in the same folder for some reason
Disable the virus scanner and see if the problem persists. Some antivirus products block access to files for a couple of microseconds after they have been written or modified. I know of Kaspersky for example.
I have a "Antivirus" retry loop in some of my batch files because of this. So one (ugly) solution is to retry the rename/remove operations a couple of times.

fgets only read the first line of file

I am trying to read a file from my .cpp file. I am using C libraries, so do not confuse on that.
So the problem is as clear as what I said in the title. fgets method can read the first line but when it comes to the second line, it cannot read neither the second line nor the rest of the file (since it exits when a problem occurs).
You can find the associated part of code:
void read_input()
{
int i = 0, N = 5;
char str[STR_SIZE], line[STR_SIZE];
FILE *fp;
fp = fopen("out", "r");
if (!fp)
{
fprintf(stderr, "error: file could not be opened\n");
exit(1);
}
for (i = 0; i<2; i++)
{
if (fgets(str, STR_SIZE, fp) == NULL)
{
fprintf(stderr, "error: failed at file reading\n");
exit(1);
}
if (feof(fp))
{
fprintf(stderr, "error: not enough lines in file\n");
exit(1);
}
if ((sscanf(str, "%s", line) != 1) )
{
fprintf(stderr, "error: invalid file format\n");
exit(1);
}
printf("%d\t%s\n", i, line);
fclose(fp);
}
}
I believe, the problem is there, because you've used fclose(fp); inside the loop. So, after the very first iteration, the fp is passed to fclose() and for any recurring use of fp in any further iteration will invoke undefined behavior as the fp is not valid anymore.
Solution: Move the fclose(fp); outside the loop.
You are closing the file in the loop! Put the fclose function outside of the loop.
for (i = 0; i<2; i++)
{
....
printf("%d\t%s\n", i, line);
fclose(fp); // <-- here, move out of the loop.
}

File open issue, after file deleted. fopen status is failing in VC++

fopen example
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
FILE * pFile;
for(int i=0; i < 1000000; i++)
{
bool ret = remove("C:\\abc.txt");
pFile = fopen ("C:\\abc.txt","w");
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
fclose (pFile);
}
else
{
printf("%d fopen() fails \n", count);
}
}
return 0;
}
Here, after remove is called, pFile = fopen ("C:\abc.txt","w");is called,
Sometimes even in C:\ the abc.txt file is not present after remove called, but the fopen pFile pointer is null.
This is reproduced some times not always. In this example this issue is reproduced 50/60 times.
Please suggest some solution.
If you have already established that is is a problem of race condition in the underlying file system, the correct way to fix it is (as suggested by BLUEPIXY) to simply remove the remove call :
pFile = fopen ("C:\\abc.txt","w");
will create the file if it does not exist and truncate it to 0 size if it exists, what is exactly what you need.
If you need to create a file surely after the file was removed, you can delay the fopen until you confirm that the old "abc.txt" file removed.
For that you need to introduce some loop to confirm it like below,
bool ret = remove("C:\\abc.txt");
FILE * rFile;
while(true)
{
rFile = fopen ("C:\\abc.txt","r");
if(rfile == null)
break; //File Removed confirmed!!
else
sleep(100); //Loop around again...
}
pFile = fopen ("C:\\abc.txt","w");
if (pFile!=NULL)

Weird string result

My program should open a file, the file path is retrieved from the command line using argv[1].
I then try to open the file using fopen but my program crashes because the filepath I use doesn't contain double backslashes so fopen doesn't work.
I've tried to write my own convert function and using print to check the result looked good at first sight.
The problem is that when I use the returned const char* as argument it gives me a weird result.. my code:
#include <stdio.h>
#include <stdlib.h>
#include <string>
const char* ConvertToPath(std::string path)
{
std::string newpath = "";
for(unsigned int i = 0; i < path.length(); ++i)
{
if(path[i] == '\\')
{
newpath += "\\\\";
}
else
{
newpath += path[i];
}
}
printf("%s \n", newpath.c_str());
return newpath.c_str();
}
bool OpenDBC(const char* path)
{
const char* file = ConvertToPath(path);
printf("%s \n", file);
FILE* dbc = fopen(file, "rbw");
if (!dbc)
return false;
return true;
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("Error, expected DBC file.");
getchar();
return -1;
}
if (!OpenDBC(argv[1]))
{
printf("There was an error opening the DBC file.");
getchar();
return -1;
}
getchar();
return 0;
}
Opening a DBC file with my program gives me the following result:
D:\\Achievement.dbc
a
So it looks like const char* file only contains 1 char of the file path, why?
You do not need the ConvertToPath function at all. Double backslashes are only needed in string literals. Never in variables such as a std::string.
I compiled your code on Linux and can not replicate your result
Running ./filereader "D:\\Achievement.dbc" results in
D:\\Achievement.dbc
D:\\Achievement.dbc
Running ./filereader "D:\\\\Achievement.dbc" results in
D:\\\\Achievement.dbc
D:\\\\Achievement.dbc
The later is what you want because command line arguments need to be escaped. Then you can remove the ConvertToPath.

Reading and Writing to a File using C++

I need to read each line in the "test.txt" file using fscanf and print to new files using fprintf. If the read line is an integer, it is written to the integer file.
Float to the float file and string to string file respectively. However, when i try to compile it and run it, nothing happens and it goes to infinite loop.
Here is my code
#include <iostream>
#include <stdio.h>
using namespace std;
void writeFloat(){
FILE *file;
FILE *file2;
float value;
file = fopen("test.txt", "r");
file2 = fopen("float.out.txt", "w");
while(!feof(file)){
fscanf(file, "%f", &value);
fprintf(file2,"%f", value);
}
fclose(file);
fclose(file2);
}
void writeInteger(){
FILE *file;
FILE *file2;
int value;
file = fopen("test.txt", "r");
file2 = fopen("int.out.txt", "w");
while(!feof(file)){
fscanf(file, "%d", &value);
fprintf(file2, "%d", value);
}
fclose(file);
fclose(file);
}
void writeString(){
FILE *file;
FILE *file2;
char value;
file = fopen("test.txt", "r");
file2 = fopen("string.out.txt", "w");
while(!feof(file)){
fscanf(file, "%s", &value);
cout<<value<<endl;
fprintf(file2, "%s", value);
}
fclose(file);
fclose(file2);
}
int main(){
writeFloat();
writeInteger();
writeString();
return(0);
}
The test.txt file contains the values:
100
1.6E-10
hey nice to meet you.
43
56
4.5E-09
what is going on?
I don't know what wrong with my code. Please help me to achieve my requirement.
feof() is never true because fscanf in writefloat() refuses to read the first letter of "hey": It's not part of a legal number. scanf then returns with 0 ("no item could be read"). That is not EOF yet, though. But you should do something about it ;-).
Besides you must check for eof after you try to read something, before you try to use it. Not before the first failed read will the eof flag be turned on, but those variables will not be assigned.
I think, adopting a different strategy might be more appropriate for your needs.
Just have one function that reads the contents of the file line by line. It checks whether the line contains an integer or a floating point number. It line does not contain any numbers, the line is written out to "string.out.txt". If the number is an integer, it is written out to "int.out.txt". If the number is a floating point number, it is written out to "float.out.txt".
With this strategy, you have to read the contents of the input file only once and process the contents of the file only once.
It also simplifies the reading of the data and checking when you have reached EOF.
#include <stdio.h>
void writeData()
{
FILE *file1 = NULL;
FILE *file2 = NULL;
FILE *file3 = NULL;
FILE *file4 = NULL;
char value;
double realNum = 0.0;
int intNum = 0;
int n = 0;
char line[256];
file1 = fopen("test.txt", "r");
file2 = fopen("string.out.txt", "w");
file3 = fopen("int.out.txt", "w");
file4 = fopen("float.out.txt", "w");
while ( fgets(line, 255, file1) != NULL )
{
// Each line can be plain old text, a floating point number, or an
// integer.
// If the line does not contain a number, assume it is a float.
// Try to read a real number.
n = sscanf(line, "%lf", &realNum);
if ( n == 0 )
{
// The line does not have a number.
// Write the line to the text file.
fputs(line, file2);
}
else
{
// We have a real number.
// Could it be just an integer?
// Read the integer.
sscanf(line, "%d", &intNum);
// How do we decide whether the number is a real number or an
// integer?
// Is 1.0 a real number or an integer?
// Assume for now it is an integer.
if ( realNum == intNum )
{
// We have an integer.
fprintf(file3, "%d\n", intNum);
}
else
{
// We have a real number.
fprintf(file4, "%lG\n", realNum);
}
}
}
fclose(file4);
fclose(file3);
fclose(file2);
fclose(file1);
}
int main()
{
writeData();
return(0);
}
That is not the common way to open and close a file in C++. It looks like a c program. Try using functions from fstream and iostream libraries. See http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm.