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)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to produce a code in Python and I feed as an input a variable of a C program. How could I do this?
If the two codes where in Python I could use "pickle'' to store the information of the first one and then read it in the second one. But for what I've been reading there is not a pickle-like way to do it in C (please correct me if I am wrong, because I know almost nothing of C) and even if there exists such a way I'm unsure of the right way to "import'' it to Python.
The data I need to save is an "array of doubles'', that actually is a dynamic allocation of the memory.
BTW: What I'm doing now is get the print of the output, save it to a file and read it in python, but I'm losing decimal precision due the rounding when printing.
You can serialize the data in python using the struct.pack function, in C you can then unpack this information again using the union data type. I will give short codes in both languages on how to do both parts. The reverse is also possible and should be easy for you to do yourself should you require it. Remember that when you're sending doubles instead of floats you need to read 8 bytes in the C code each time.
In Python:
import struct
doublesArray = [5.0, 1.2, 3.4, 8.6]
file = open("transferdata", "wb")
for i in range(len(doublesArray)):
file.write(struct.pack('f', doublesArray[i]))
In C. By the way I took this code from this post:
#include <stdio.h>
#include <stdlib.h>
union
{
char asBytes[4];
float asFloat;
} converter;
int main(void)
{
FILE *fileptr;
char *buffer;
long filelen;
fileptr = fopen("transferdata", "rb");
fseek(fileptr, 0, SEEK_END);
filelen = ftell(fileptr);
rewind(fileptr);
buffer = (char *)malloc((filelen+1)*sizeof(char)); // Enough memory for file + \0
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr);
int i = 0;
while(i < filelen)
{
converter.asBytes[0] = buffer[i];
converter.asBytes[1] = buffer[i + 1];
converter.asBytes[2] = buffer[i + 2];
converter.asBytes[3] = buffer[i + 3];
i += 4;
char msg[32];
snprintf(msg, 32, "%f ", converter.asFloat);
printf(msg);
}
return 1;
}
[EDIT]: I see I wrote the exact opposite of what you need. I did not do that on purpose. However, I think you have enough information to figure out how to do the reverse on your own now.
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 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.
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.