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

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)

Related

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.
}

Debug Assertion Failed VS2010

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.

How do I compile/open such a file

I don't know how to compile this class, it exits with -1 when I compile it in visual/codeblocks. Do I have to use command line? How do I do that?
int main(int argc, char* argv[]) {
if( argc <= 1 )
return -1;
Chunk::init();
FILE *f = fopen(argv[1], "rb");
Chunk *obj = read_chunk( f );
fclose( f );
delete obj;
if( argc > 2 )
return 0;
OpenGL ogl(&argc,argv);
}
OpenGL ogl(&argc,argv);
}
As the code suggests, you have to supply a command-line option!
FILE *f = fopen(argv[1], "rb");
The command-line argument should be some file that will be open by this program. Since you only paste a snippet, I don't know what this program is for.
But say the compiled binary is a.exe, then you should run it as:
a.exe A_FILE_NAME

Code crash if there is no print on the loop, how can I fix?

My code below is to do a filter in a PCM file (a music file full of short ints), apply a filter and make an output.
When I execute it (press F9), there is sometimes in which it will succeed and others that it will crash my executable, but if I put a printf/cout on it, making the program last longer, it will increase its chances of not crashing.
Its very bizarre, I don't know what is happening so I can't fix it, please take a look below in my code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
short *vetor_entrada, *vetor_saida;
char nomeArquivoEntrada[50] = "sweep_100_3400.pcm", nomeArquivoSaida[50] = "saida.pcm";
size_t tamanhoArquivo;
int lerEntrada(){
FILE * pFile;
long lSize;
size_t result;
pFile = fopen ( nomeArquivoEntrada , "rb" );
if (pFile==NULL) return -1;
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
tamanhoArquivo=lSize/sizeof(short);
vetor_entrada = (short*) malloc (sizeof(short)*lSize);
vetor_saida = (short*) malloc (sizeof(short)*lSize);
if (vetor_entrada == NULL) return -1;
result = fread (vetor_entrada,sizeof(short),lSize,pFile);
if (result != lSize) return -1;
fclose (pFile);
return 0;
}
int escreverSaida(){
FILE * pFile;
pFile = fopen (nomeArquivoSaida, "wb+");
fwrite (vetor_saida , sizeof(short), tamanhoArquivo, pFile);
fclose (pFile);
}
void processamento(int k){
float *vetor_coeficientes = (float*) malloc (sizeof(float)*k);
short *vetor_amostras = (short*) malloc (sizeof(short)*k);
for(int i=0;i<k;i++){
vetor_coeficientes[i]=(float)1/(float)k;
vetor_amostras[i]=0;
}
for(int j=0;j<tamanhoArquivo;j++){
vetor_amostras[0]=vetor_entrada[j];
short aux=0;
for(int m=0;m<k;m++){
aux += vetor_coeficientes[m]*vetor_amostras[m];
}
vetor_saida[j]=aux;
for(int n=k;n>0;n--){
vetor_amostras[n] = vetor_amostras[n-1];
}
}
}
int main(){
lerEntrada();
processamento(32);
escreverSaida();
return 0;
}
The loop in "processamento" function (the 'j' increasing one) is the main problem (as far as I've seen), if I put printf("%d",j) in it, probably won't crash.
Here is some PCM file to test it with:
https://www.mediafire.com/?3l3iq8553jcy7dk
How can I fix the crashing?
This looks wrong
for(int n=k;n>0;n--){
vetor_amostras[n] = vetor_amostras[n-1];
The range of vetor_amostras is 0 .. k - 1. You are assigning to [k].

Segmentation fault executing file writing using FILE pointer

I get a "Segmentation fault" for the following C++ code:
#include <cstdio>
int main(int, char**) {
FILE *fp;
fp = fopen("~/work/dog.txt", "w");
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
Your path is invalid and will never work, thus fopen sets fp to NULL and you get a segfault. Hint: the ~ character is expanded by the shell, you can't use it in an argument to fopen.
A correct, safe implementation of what you're trying to do might look as follows. This is tested. It's also the reason why sane people don't write in C unless they have no other way of doing it :)
// main.cpp
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
int main(int, char**)
{
const char * home = getenv("HOME");
if (home == NULL || strlen(home) == 0 || access(home, F_OK) == -1) abort();
const char * subPath = "/work/dog.txt";
char * path = (char*)malloc(strlen(home) + strlen(subPath) + 1);
if (path == NULL) abort();
strcpy(path, home);
strcat(path, subPath);
FILE *fp = fopen(path, "w");
if (fp != NULL) {
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
free(path);
}
A few things:
you need to check fp for NULL before using it, else you'll get a segfault whenever the file isn't found.
you need to resolve the full path before passing it to fopen (fopen doesn't know what to do with "~")
example:
FILE *fp = NULL;
char path[MAX];
char *home = getenv ("HOME");
if ( home )
{
snprintf(path, sizeof(path), "%s/work/dog.txt", home);
// now use path in fopen
fp = fopen(path, "w");
if ( fp )
{
fprintf(fp, "timer, timer3, timer5, timer6, timer7");
fclose(fp);
}
else
{
std::cout << "your dog is missing" << std::endl;
}
else
{
std::cout << "You are homeless" << std::endl;
}
Segfault happens is the file you're trying to open does not exist. This has nothing to do with Qt.
Test for the nullity of 'fp' and handle the error correctly. Something like
FILE *fp = fopen("/path/to/work/dog.txt", "w");
if (fp == NULL)
{
printf("File does not exist.\n");
// throw exception or whatever.
}