I am making a c program that can save matrices and vectors in CSV files so I can then perform operations between them. In one of my functions I create a matrix with random numbers and then save it inside a CSV file.
The problem is that I don't know how to create a different file every time the function is run so each array can be stored in a different CSV file. Because of this I have to save all the matrices inside the same file which makes the rest of the process a lot harder. How could I make the function that makes a different file every time without it having completely random names.
Here is a link to the project in replit
How could i make the function that makes a different file every time without it having completely random names.
Some possible solutions:
use timestamp as part of filename
use counter
For a timestamp, example code:
char filename[80];
snprintf(filename, sizeof(filename), "prefix.%d", time(NULL));
FILE *fout = fopen(filename, "wt");
For a counter, use the same code as above, but check if the file prefix.${counter} exists (see man access). If it does, increment the counter and try again. If it doesn't, use the filename.
Related
I have a program based on a struct with different information.
In this program you can for example add people and delete people etc. I already have all this done, so the program it self is done. But the files are not.
So I am trying to write a code that "saves" if I would for example add a person and this would "save" when I choose to exit the program. And a code that "restores" the people in the file in the beginning of the program.
Does any one have any ideas or tips? I'm new to programming and trying to learn. I have been sitting with this for a few days.
Before I "restore" I ask for an file to open and if this file does not exist a new one is created and this works. So if I would have a file with 3 employees and I would open this file I would want to restore them and then being able to add more employees to the file etc.
You have to write (and to read) in two steps: first the struct, and then the array the struct points to.
Code fragment for writing (a.o. without error checking, that is however needed):
#include <stdio.h>
// ...
employees emp;
const char* filename="your_filename";
// populate emp;
FILE* file = fopen(filename,"w");
fwrite(&emp,sizeof(employees),1,file);
fwrite(emp.pic,sizeof(int),emp.imageCount,file);
fclose(file);
Now you have the array after the struct in your file. Read it in the same way:
FILE* file = fopen(filename,"r");
fread(&emp,sizeof(employees),1,file);
emp.pic=calloc(sizeof(int), emp.imageCount);
fread(emp.pic,sizeof(int),emp.imageCount,file);
Please don't forget to check for errors (see man fopen|fread|fwrite|calloc). In case you have several structs, you must repeat the two steps for any element.
What is the platform? For Windows there is simple format of .INI files with contents like:
[Employee_1]
id=123
name=Smith
imageCount=2
...
You can use GetPrivateProfileString/GetPrivateProfileInt and WritePrivateProfileString API functions to read and store the information. Use separate section for each employee. One common section is necessary to store the number of employee sections.
I am trying to take an input from a text file in this format:
Processed_kplr010074716-2009131105131_llc.fits.txt
Processed_kplr010074716-2009166043257_llc.fits.txt
Processed_kplr010074716-2009259160929_llc.fits.txt
etc.... (there are several hundred lines)
and use that input to name my output files for a Matlab loop. Each time the loop ends, i would like it to process the results and save them to a file such as:
Matlab_Processed_kplr010074716-2009131105131_llc.fits.txt
This would make identifying the object which has been processed easier as I can then just look for the ID number and not of to sort through a list of random saved filenames. I also need it to save plots that are generated in each loop in a similar fashion.
This is what I have so far:
fileNames = fopen('file_list_1.txt', 'rt');
inText = textscan(fileNames, '%s');
outText = [inText]';
fclose(fileNames)
for j:numel(Data)
%Do Stuff
save(strcat('Matlab_',outText(j),'.txt'))
print(Plot, '-djpeg', strcat(outText(j),'.txt'))
end
Any help is appreciated, thanks.
If you want to use the save command to save to a text file, you need to use -ascii tab, see the documentation for more details. You might also want to use dlmwrite instead(or even fprintf, but I don't believe you can write the whole matrix at once with fprintf, you have to loop over the rows).
I have 80+ text files which I am current'y reading into the program using dirent.h. This is placing them in an array, I am throwing them each through an algorithm which will compare the contents of each file to the other contents within that file and provide me with a percentage of how identical things within the file are. While doing that it will store the name of the file in ArrayName[i] and the percentage in ArrayPercent[i].
I am pretty sure I know how to print those array values to a file, that is not the problem, the problem is using a variable as the filename. My current thoughts are something along the lines of
fprintf(**DIRECTORY HERE**,"%s %d", ArrayPercent[i], ArrayName[i][]);
The first time through a loop ArrayName[0] needs to go in DIRECTORY HERE as the filename.txt and the second time through ArrayName[1] needs to go there as filename1.txt for argument sake and so forth for the remainder of ArrayName.
You can create multiple filename0.txt, filename1.txt, etc using:
for (i=0; i<n; i++) {
char buf[32];
sprintf(buf, "filename%d_%s_%d", i, ArrayName[i], ArrayPercentage[i]);
}
I have opened a file using a and r+ but when I use fseek and ftell the file pointer is always 0.
My file looks like this:
1 -3
2 -8
And I want to add another line between the two but it is added in the end after the last line.
Someone in another forum said that when you open the file in append the pointer is always zero and you have to open it in r+ and if that doesn't work "you have to read the complete data and then insert the data in the variables and write it back." but I don't understand what they mean by that.
Can anyone help with inserting numbers in the middle of a file?
Thanks!
Would something like this work?
To transfer the data?
rewind(fp);
fscanf(fp,"%d",&ch);
fprintf(fp1,"%d",ch);
fseek(fp,1,0);
fscanf(fp,"%d",&ch);
fprintf(fp1,"%d",ch);
Like others already said, there's no easy way to insert data in the middle of a file. If you really want to do this, you can implement the following steps:
Create a second file
Copy all data before the place you want to insert to the second file
Insert the line you want to the second file
Copy the remaining data to the second file
Delete the original file
Rename the second file
Other approach is using binary files instead of text files. Although binary files are a bit harder to learn, once you understand how they work you'll see that working with them is much like working with arrays. To perform this task, for example, you'd not even need to use an auxiliary file.
There is no open mode that will allow you to "insert" data into a file at a random point. The only place you can add data without overwriting existing data is the end of the file (what you get opening with mode "a").
If you want to insert at a random position, you need to do it yourself.
One of the easier ways is to re-write the file completely (transfer the start of the old file to a new file, add your data to the new file, transfer the rest of the old file, and rename/overwrite at the end).
The hard way: you need to "shift" all the data from your insertion point to the end-of-file manually. That's not trivial to get right.
There isn't an easy way to insert data in the middle of the file. A file is basically an array of characters. To add a character in the middle, you need to copy everything following your insertion point down one location. With a file you need to read the data that follows and write it after your addition.
Generally, when you want to do something like this you create a new file. You copy the old file into it up to the point where you want to insert, then you write the data you want to insert, then you copy the rest of the old file. Finally, you rename the new file to the old file.
I've got a service which runs all the time and also keeps a log file. It basically adds new lines to the log file every few seconds. I'm written a small file which reads these lines and then parses them to various actions. The question I have is how can I delete the lines which I have already parsed from the log file without disrupting the writing of the log file by the service?
Usually when I need to delete a line in a file then I open the original one and a temporary one and then I just write all the lines to the temp file except the original which I want to delete. Obviously this method will not word here.
So how do I go about deleting them ?
In most commonly used file systems you can't delete a line from the beginning of a file without rewriting the entire file. I'd suggest instead of one large file, use lots of small files and rotate them for example once per day. The old files are deleted when you no longer need them.
Can't be done, unfortunately, without rewriting the file, either in-place or as a separate file.
One thing you may want to look at is to maintain a pointer in another file, specifying the position of the first unprocessed line.
Then your process simply opens the file and seeks to that location, processes some lines, then updates the pointer.
You'll still need to roll over the files at some point lest they continue to grow forever.
I'm not sure, but I'm thinking in this way:
New Line is a char, so you must delete chars for that line + New Line char
By the way, "moving" all characters back (to overwrite the old line), is like copying each character in a different position, and removing them from their old position
So no, I don't think you can just delete a line, you should rewrite all the file.
You can't, that just isn't how files work.
It sounds like you need some sort of message logging service / library that your program could connect to in order to log messages, which could then hide the underlying details of file opening / closing etc.
If each log line has a unique identifier (or even just line number), you could simply store in your log-parsing the identifier until which you got parsing. That way you don't have to change anything in the log file.
If the log file then starts to get too big, you could switch to a new one each day (for example).