Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In the below code, line[] array contains names of all image files contained in a folder. We are just reading the names dynamically and sending the file names one by one to a function function_foo as given in the code. When there are 8 images the code is executing as expected. But as soon as we increase the number of image files in the folder to any number above 8, the process gets terminated and returns -1. Please suggest.
FILE **fp;
struct Structure_Name data[100];
fp = malloc( sizeof(FILE *) * 10000);
for(i=0;i<total; i++)
{
sprintf(fName,"/home/souvik/Images/%s",line[i]);
printf("%s\n",fName);
fp[i] = fopen(fName, "rb");
data[i]=function_foo(fp[i],(data[i]));
}
It is a really bad idea to open 10000 files at the same time. I'd recommend you to change this logic: to read content of these files one by one, and to send this content to your function function_foo. But currently your code tries to fopen very big number of files without closing of it. I expect it is the main problem (i.e. it seems that in your environment maximal number of files that can by opened is 8).
See also:
Maximum number of files that can be opened by c "fopen" in linux
Is there a limit on number of open files in Windows
Update:
Since you don't need an array of all pointers, you can try following version. Do you see the same problem in this case?
FILE *fp;
struct Structure_Name data[100];
for(i=0; i<total; i++)
{
sprintf(fName,"/home/souvik/Images/%s", line[i]);
printf("%d of %d, %s\n", i, total, fName);
fp = fopen(fName, "rb");
if (fp != NULL)
{
data[i]=function_foo(fp,(data[i]));
fclose(fp);
} else
{
printf("A null pointer is returned by fopen()");
}
}
#ALL, Thanks for your active help.
Now the problem is solved. The root cause of the problem was that, while the program was looping through all the images it was storing the image data in data[i] , i.e. data[1], data[2], data[3], data[4]......... the data is temporarily stored in \var folder during program execution. after reading 9 image files the total size of 9 images (data[1]+data[2]+data[3]+..... data[9]) exceeds the size of \var in our machines. We simply de-allocated the space allocated for the structure variable data[i] after each iteration. This solved the problem.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
wanna access multiple files using C.
For suppose, I have file with that names
1.txt
2.txt
n.txt
I am looping through all of the files till n. But I am only getting data from the first file which is 1.txt. and that data is repeating n times. (n represents the number of files).
So, how to get data from each file. Each file contains different data.
for(i = 0; i < fileQuantity; i++) {
sprintf(buffer, "%d", i);
ptr = fopen(strcat("C:\\TURBOC3\\FILES\\", strcat(buffer, ".txt")), "r");
fscanf(ptr, "%s", &adminUsername);
fclose(ptr);
outtextxy(225, 140 + distance, adminUsername);
distance += 30;
}
I am surprised that you can read even from one file :). strcat("C:\\TURBOC3\\FILES\\", will not work as it invokes Undefined Behaviour (attempt o modify string literal, access out of bounds).
Simply do:
sprintf(buffer, "C:\\TURBOC3\\FILES\\%d.txt", i);
ptr = fopen(buffer, "r");
or better
snprintf(buffer, buffer_length, "C:\\TURBOC3\\FILES\\%d.txt", i);
I would suggest using something more modern than TurboC 3 :) (at least from this century)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to run a C source file and the result was it got stuck in an infinite loop. I literally copied and pasted the same code into a new source file, Untitled1, and it ran fine. Both the original and the new source file are saved on the desktop. Why is this happening?
#include <stdio.h>
int main()
{
int i, j, d, a;
scanf("%d %d", &i, &d);
printf("%d\n", i);
a = 1;
while(i>1)
{
i = i%d;
for(j = 1; j<=a; j++)
{
printf(" ");
}
printf("%d\n", i);
d = d/100;
a++;
}
//////////
return 0;
}
Just a simple exercise from CodesDope. The goal is to print
1010101
10101
101
1
Which you get by entering i=1010101 and d=1000000.
I cannot doubt your experience but I'm not sure your conclusion is correct. First we don't run source code, it has to be compiled first. This leaves open the possibility that you have an old executable, i.e. an executable that doesn't reflect the code. The same code compiled the same way should produce the same runtime behavior (given that that code logic is correct).
Since all the variables are integer the d variable can become 0 and if this happens before i becomes less than or equal to 1 the i%d would result in a divide by zero error. Trying your code on repl.it with i = 1000 and d = 77 generates a floating point exception, but different compilers/environments may surface that undefined state differently (though all should produce an error state).
My advice is to delete both your compiled executables and any object files (clean your project), then recompile and compare results. If you still see different behavior based on the same output, then carefully compare your source files (or 'diff' them if you are on a unix'y system). If you still find a discrepancy, update your question with both source files (even if you find them identical), the compiler (name/version) and environment (OS/version) you are using.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a section of code that fails when I try to use fclose to close an output file. The code looks as follows:
void WriteArrayForCheck(int numLines, double **Array) {
char outFile2[300];
sprintf(outFile2, "OutputArray.txt");
FILE *outputFile2;
outputFile2 = fopen(outFile2, "w");
int incRow;
for (incRow = 0; incRow < numLines - 1; incRow++) {
fprintf(outputFile2, "%lf,%lf,%lf\n",
Array[incRow][1], Array[incRow][2], Array[incRow][3]);
}
fclose(outputFile2);
}
I end up with an error related to my executable that says:
free(): invalid next size (normal): 0x0000000001ce1710 ***
and a whole bunch of other stuff that doesn't make sense... The ironic thing is if I comment out the line related to fclose, then the program does not crash and runs perfectly fine... I have not had this issue before. I am sure that my matrices are incremented properly as well. PLease let me know what you think.
The code as posted does not seem to have an obvious problem.
Note however that:
You should always check the return value of fopen() and report failure instead of risking undefined behavior by passing NULL to fprintf and/or fclose.
You should simplify the first few statements as FILE *outputFile2 = fopen("OutputArray.txt", "w");
If you do something more complicated to compute the filename, post it as the problem may lie in seemingly harmless code that you omitted.
The fprintf conversion specifier for double is %f, the l modifier is useless and ignored in this context. It is required in fscanf() to distinguish between float and double, but not needed in fprintf because float values are always passed as double to variable argument functions.
The index values 1, 2 and 3 might be incorrect, arrays are 0 based in C.
Stopping the loop at incRow < numLines - 1 is unexpected too, why omit the last row of the matrix? If you really mean it, a comment would be helpful to clarify why.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have to remove from a file the bytes found at even addresses in C. I have opened the file for rw, I have found its length and put the content in a buffer. How can I loop every byte? I have tried this, to see what do I have in buffer:
for(i=0;i<len;i=i+2)
printf("%d",buffer[i])
But in the buffer are saved the ASCII codes of the characters. Does it have any impact on my future line codes? And I have to write the desired output in another file, or I can just erase the initial content of the file and write in the file the modified buffer?
If you intend to write the buffer back to the file, then simply overwrite the buffer in this manner:
int front = 0;
int back = 0;
while (front < len) {
buffer[back] = buffer[front];
back++;
front += 2;
}
int newLen = back;
// Write the buffer to disk using the the new length (newLen)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am writing C-program that in the end will contain two large 2-dimensional arrays that I need to export to two csv.files.
The arrays (doubles) are 10000 rows long, and between 8 and 30 columns long, depending on what the user define, example below:
int NOS = 10000;
int Tau_length = 15;
Energy_system_Array[NOS][Tau_length];
I have created two file pointers:
FILE *fp1, *fp2;
At the end of the program, I have written these lines:
int array_rowit, array_colit;
fp1 = fopen("Energyarray.csv", "w");//create a file
if (fp1 == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
for (array_colit = 0; array_colit<Tau_length; array_colit++){
for (array_rowit = 0; array_rowit< start_measure; array_rowit++){
fprintf(fp1, Energy_system_array[array_rowit,array_colit]);
fclose(fp1);
}
}
But when I compile the c-code, this is the message I get:
main.c: In function 'main':
main.c:413:22: error: incompatible type for argument 2 of 'fprintf'
fprintf(fp1, Energy_system_array[array_rowit,array_colit]);
^~~~~~~~~~~~~~~~~~~
In file included from main.c:1:0:
C:/MinGW/x86_64-w64-mingw32/include/stdio.h:378:15: note: expected 'const char * restrict' but argument is of type 'double'
int __cdecl fprintf(FILE * __restrict__ _File,const char * __restrict__ _Format,...);
^~~~~~~
I am a real novice when it comes to C-programing, so I hope someone can help me with this.I have searched around for different guides, but I haven't found any that describes my situation exactly.
I should mention that the csv files should be overwritten for each run of the program. It cannot save the values from an earlier run of the program.
To write the whole array as CSV, use:
for (array_colit = 0; array_colit<Tau_length; array_colit++){
for (array_rowit = 0; array_rowit< start_measure; array_rowit++){
fprintf(fp1, "%lf%s",Energy_system_array[array_rowit,array_colit],
(array_rowit<start_measure-1?",":""));
}
fprintf(fp1,"\n");
}
fclose(fp1);
Notes:
append a comma after each value but the last one
add a newline after every row
close the file only once everything has been written out.