can not create text files in a c program - c

I want to create 1000000 text files in a folder, by a c program, but it creates only 508 text files in a folder. My code is:
int i, j;
char temp[100];
for(j=0;j<100;j++)
temp[j]= NULL;
for (i=0;i<1000000;i++)
{
sprintf(temp,"%ld.sift",i);
fopen(temp,"w+");
}

Also call fclose after you've created the file - you can't have 1000000000000 files opened at the same time.

Use the below code:
int i, j;
char temp[100];
FILE *fp;
memset(temp , '\0' , 100 );
for (i=0;i<1000000;i++)
{
sprintf(temp,"%ld.sift",i);
fp = fopen(temp,"w+");
fclose(fp);
}

As others pointed out by others the code seems to be missing to fclose() the file fopen()ed, so the system most probably runs out of resources keeping all those file open.
To fix this just close them, before creating new ones.
If on Linux and you just want to create the (empty) files without opening them the mknod() function can be used for this.

Related

File deletes content after stopping execution in C

So I'm trying to save a bunch of data in a text file to load it later.
The function prints the data to the text file correctly, but when I stop the execution and start it again to see if it loads, there is no data in the text file.
It happens right after I stop the program.
Here is the function used:
void saveGame(t_game game, int width, int height){
FILE * file= fopen("save.txt", "w+");
int i = 0;
int j = 0;
fprintf(file,"%d%d", game.origbomb, game.wincount);
for(i=0;i<width;i++){
for(j=0;j<height;j++){
fprintf(file,"%c",game.map[i][j]);
}
}
for(i=0;i<width;i++){
for(j=0;j<height;j++){
fprintf(file,"%c",game.bombmap[i][j]);
}
}
fclose(file);}
You should use:
FILE * file= fopen("save.txt", "a+");
This will append to the file.
If you "stop the execution", then I suppose fclose was not called, then only flushed data will be present in the file. Use fflush to manually force the file content to be flushed just after you called fprintf.
Also, consider checking file content from a file editor rather than a program. Maybe you are not reading it correctly.
Finally, consider opening the file with "a" option if you mean to extend an existing content without creating a new file.

File pointer still NULL after inizialization?

Hi guys i have a problem when I try to open a file. In a function when i try to read an existing text file, after i initialized the file pointer i still get the error "cannot open the file", this is the code:
FILE * fp;
fp = NULL;
fp=fopen("results.txt","r");
if(fp==NULL){
printf("error!");
exit(1);
}
using the debugger i can see the fp initialized to NULL, as requested. In the next order i can see its value changed to '0x751d9c68'.
So now it's not NULL, but the program still prints error.
PS: I used the same code to open another file in another program (that works): as always the initial value of fp is NULL, then it's changed to '0x751d9c68' (yes, it has the same value in both programs), but this time works, because fp is in fact different from NULL.
PPS: I'm using Codelite, if that helps.
EDIT: adding a printf("%p\n", fp); prints this "751D9C68"
Atleta * leggiRisultati (char fileName [], int * dim){FILE * fp; int count, i;
Atleta temp;
fp = NULL;
fp=fopen(fileName,"r");
printf("%p\n", fp);
if(fp==NULL){
perror("Error");
}
while (fscanf (fp, "%s%s%d%d%d", temp.cod, temp.nome, &temp.tN, &temp.tB, &temp.tC)== 5)
count ++;
rewind (fp);
Atleta * atl = (Atleta*) malloc(count * sizeof(Atleta));
for (i=0; i<count; i++){
int nr = fscanf(fp, "%s%s%d%d%d",atl[i].cod, atl[i].nome, &atl[i].tN, &atl[i].tB, &atl[i].tC);
//just controlling if the reading is done properly
if (nr < 4) {
printf ("cannot read the file %s",fileName);
exit (1);
}
} fclose(fp);
return atl;
}
I then use this function in this main
int main (){ int dim; Atleta * a; int i;
a = leggiRisultati("risultati.txt", &dim);
for (i =0; i<dim;i++){
stampaRisultato(a[i]);}
return 0;
}
Where "stampaRisultato" prints a line of the file just read and "Atleta" is a struct defined as:
typedef struct {
char cod[5];
char nome[21];
int tN, tB, tC;
}Atleta;
And last, yes the text file is in the same directory as my executable, yes I have the permission to open the file, the file contains a certain number of lines with 2 strings and 3 int each.
Your code should work, I can only think of 3 things that may cause this issue.
In my experience, it's oftentimes the simplist mistakes that get you, because you're so focused on the more complex elements that some things slip your mind. I can't see the rest of your program, so forgive me if any of these answers seem patronizing. Here are the first things I would check:
1.) file permissions. Make sure you're a user with permission to access and/or change the file in question. This is a pretty easy fix on linux, but I don't know about windows.
2.) file location. Make sure your text file is in the same directory as your executable. You'll need to do this if you don't specify file location.
3.) #include statements. Sometimes even the best of us get too excited to get into the bulk of our program, and we forget to include stdio.h and/or stdlib.h. If this is the case you may run into an issue where you set the file pointer to null, and then the fopen function doesn't run, so your pointer remains null.

When writing to a file, fputs() does not change line

I'm currently trying to create a database in C, using a .txt document as the place to store all the data. But I can't get fputs() to shift line, so everything that my program writes in this .txt document is only on one line.
int main(void){
char c[1000];
FILE *fptr;
if ((fptr=fopen("data.txt","r"))==NULL){
printf("Did not find file, creating new\n");
fptr = fopen("data.txt", "wb");
fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
fputs("//This text file contain information regarding the program 'monies.c'.\n",fptr);
fputs("//Feel free to edit the file as you please.",fptr);
fputs("'\n'",fptr);
fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",fptr);
fputs("sum = 2000 //how much money there is, feel free to edit this number as you please.",fptr);
fclose(fptr);
}
fscanf(fptr,"%[^\n]",c);
printf("Data from file:\n%s",c);
fclose(fptr);
return 0;
}
This is my testing document.
I feel like I've tried everything and then some, but can't get it to change line, help is much appreciated.
Btw. The output looks like this:
There are two issues in your program :
You should specify "w" rather than "wb" so that the file is read and written as text rather than binary. Although in some systems this makes no difference and b is ignored.
The part for file reading should be in an else, otherwise it executes after file creation with fptr not containing a valid value.
This is the code with those corrections. I do get a multiline data.txt with it.
int main(void){
char c[1000];
FILE *fptr;
if ((fptr=fopen("data.txt","r"))==NULL){
printf("Did not find file, creating new\n");
fptr = fopen("data.txt", "w");
fputs("//This text file contain information regarding the program 'mon
fputs("//This text file contain information regarding the program 'mon
fputs("//Feel free to edit the file as you please.",fptr);
fputs("'\n'",fptr);
fputs("(Y) // Y/N - Yes or No, if you want to use this as a database",
fputs("sum = 2000 //how much money there is, feel free to edit this nu
fclose(fptr);
}
else
{
fscanf(fptr,"%[^\n]",c);
printf("Data from file:\n%s",c);
fclose(fptr);
}
return 0;
}

'fopen' in C can't open existing file in current directoy on Unix

I am using fopen(3) in C to read file and process it. The file is present in current working directory where the binary exists, but I am unable to read the file (Linux environment / Cygwin environment).
Here is the sample code:
C code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *inFile;
static char fileName[255];
int process_file(FILE *inFile)
{
char ch;
inFile = fopen(fileName,"r");
if (inFile == NULL)
{
perror(fileName);
exit(1);
}
else
{
// Process file
}
fclose(inFile);
return 0;
}
int main(int argc, char *argv[])
{
printf("Enter filename to process \n");
scanf("%s", fileName);
process_file(inFile);
getchar();
return 0;
}
I have file permissions set to 777 in the current directory. The resulting binary as well as my source code reside in this directory where the input file exits. Why is the file not opened?
Update :
This question was written in few years back and this code could be improved a lot.
1. The process file should accept char * or char array instead of file pointer
2. unused variables can be removed
3. unused libraries or include files can be removed
4. Can make use of argv to accept filename with path from cmdline
5. return instead of exit in process_file and also proper return code instead of returning 0 from process_file.
I should have asked this question little more elaborate...
I had three functions to process the same file, like process_fil1e1(), process_file2() and process_file3() even though I called fclose() in all three functions. Somehow the file handle was not closed that properly or the file pointer pointed to EOF or some undefined behavior. It was not working fine.
When I used a single process file and rewind() together, it worked fine...
Be sure to input file name with its extension. This may cause problems with reading the file.
If you know the extension of the file you can input only the name and after that make the program add the extension. After scanf("%s", fileName); add strcat(fileName, ".txt"); if you want to enter only the name without extension and the file you read has extension .txt.
Your inFile and fileName variables are extern so you don't need to have arguments for the function process_file();, any function can access those variables.
You can change function int process_file(); to void process_file(); and delete return 0, you don't need that.
You have declared the inFile and fileName as global. You should change your function prototype from
int process_file(FILE *inFile)
to
int process_file()
This would at least make your program more clear. Now regarding your problem: It would almost certain be that you are doing something wrong in the input file (like not putting in the file extension) in your input. Remember, you need to pass the complete file name (including the extension which on some systems like Windows (by default) would be hidden). Otherwise, the logic looks correct to me, and it should work fine.

Matlab Crahes upon fopen in Mex File

I have a little experience with Matlab, but am new to the mex environment.
What I am trying to do is to save some values I compute to a txt file in my C routine.
For the sake of simplicity I am using the example arrayProduct.c from MathWork's Create C Source File guide here to elaborate.
I modified the example code in the following way:
void arrayProduct(double x, double *y, double *z, mwSize n)
{
mwSize i;
/* multiply each element y by x */
FILE *f = NULL;
f = fopen("log_test.csv", "rb");
for (i=0; i<n; i++)
{
z[i] = x * y[i];
fprintf(f, "%g\n", z[i]);
}
fclose(f);
}
So I added the declaration of f, the fopen, the fprintf and the fclose commands.
I am using MS Visual Studio C++ 2013 Professional (C) as a compiler and the code compiles just fine.
Through uncommenting all my changes and introducing them bit by bit again I was able to find out that Matlab crashes at the fopen command.
I wasn't able to find useful help here or elsewhere, so any suggestions are very welcome. Thanks very much in advance!
Kind Regards
Philipp
Use w+ or r+ when using fopen, depending on what you want to do with the file and whethe you want to create it or simply open it.
From (http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm)
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a" Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.
Thanks for the helpful comments, especially by RobertStettler!
The problem was with the mode I opened the file with. it should rather be r+, w+ or a+.

Resources