Reading file into array - c

I have these a file in a c program which consist of a string and 4 doubles and 2 integer in one line and there is a total of 28 lines, i want to read this file and load the data into an array. can someone help me solve this.

Split up your problem into sub-tasks:
Open the file using fopen
Allocate a buffer (array) to store the doubles
Create a loop while there is more to read
read in a single double into the array
Go to the next iteration

Related

How can i read a specific char inside a file?

This would be enough to read the first character 'a' inside fp
file.txt
abcdef
// readchar.c
FILE *fp = fopen("file.txt", "r");
int c = fgetc(fp);
but how can i read (e.g.) the 3rd character?
A text file is a kind of sequential file. To read a specific item, you must read everything preceding it in the file.
Operating systems let you read a file anywhere by moving a so called file pointer. The position in the file where read take place can be changed by seeking into the file. There are several ways to handle file I/O. The one you found invoke fopen to open the file and get a file pointer, fgetcto read the next character where the file pointer points and advance it by one character. You have fgetsto read a complete line. fseek to more the file pointer somewhere else. fcloseto close the file. And other similar function.
Back to the text file. Assuming we have a file containing: two lines containing:
Hello world,
Programming rocks!
If you want to read the 5th character of the first line, it is easy: just position the file pointer with fseek to the 5th position in the file (the first character is at position zero). Then read it with fgetc.
Now if you need to read the 5th character of the second line, whatever the first line is, you cannot use fseek because you don't know the length of the first line without reading the line first.
To read the Nth character on the Mth line, you must read M lines, throwing away data except the last one (You simply read all line in a for/loop into the same buffer). And then access the Nth character in the buffer where you just read the last line. Make that buffer an array of char and you have direct access to the Nth character.

reading n bytes from a binary file until end of file in verilog

I have a binary file. I need to read 512 bits every time from it until the file ends and pass it as input to my design. I am using readmemh/readmemb to read from the file. but we have to specify the size of memory array before readmemh to pass as its argument. so if we don't know the depth of the register how can we read the complete binary file.
reg [511:0]packet[1:0];
$readmemh("abc.bin",packet); //this abc.bin has 237kb size
what should be the depth of memory 'packet'?
You have a few options
If there is a maximum possible size for the file, just declare the array with the maximum size needed. The remaining elements will be left uninitialized (X) by $readmemh.
Pass a parameter or macro definition on the command line with the array size when you compile your design. The commands will depend on the tool you're using.
Instead of reading the entire file into an array, read it one line at a time using $fscanf(fd,"%h", value). The value can be applied to your inputs as needed.
do begin
repeat (64) begin
code = $fscanf(fd,"%h", value); // get byte
pattern = {pattern,value}; // shift into pattern
end
send_to_dut(pattern);
end while (code == 1);
The $readmemh method is not ideal for this type of continuous data processing.
Instead I would use the same method you would in standard programming language:
Open a file, read the data you need from it, close the file. This way you can process files of many megabytes size, but you do not need many megabyte of storage.
fd = $fopen(filename,"rb");
if (fd==0)
begin
$display("%m #%0t: Could not open file '%s'",$time,filename);
$stop;
end
else
begin
$display("%m #%0t: Opened %s for reading",$time,filename);
file_is_open = 1'b1;
end
if (file_is_open)
value= $fgetc(fd);
WARNING:
This uses a binary file. Your $readmemh uses an ASCII file. You can, if you want, read an ASCII file but then you have to do the ASCII to hex conversion yourself writing a small Verilog function.

How do you scan redirected files in C (STDIN)?

Say I'm calling a program:
$ ./dataset < filename
where filename is any file with x amount of line pairs where the first line contains a string and second line contains 10 numbers separated by spaces. The last line ends with "END"
How can I then start putting the first lines of pairs (string) into:
char *experiments[20] // max of 20 pairs
and the second lines of the pairs (numbers) into:
int data[10][20] // max of 20, 10 integers each
Any guidance? I don't even understand how I'm supposed to scan the file into my arrays.
Update:
So say this is my file:
Test One
0 1 2 3 4 5 6 7 8 9
END
Then redirecting this file would mean if I want to put the first line into my *experiments, that I would need to scan it as such?
scanf("%s", *experiments[0]);
Doing so gives me an error: Segmentation fault (core dumped)
What is incorrect about this?
Say my file is simply numbers, for ex:
0 1 2 3 4 5 6 7 8 9
Then,
scanf("%d", data[0][0]); works, and will hold value of '1'. Is there an easier way to do this for the whole line of data? i.e. data[0-9][0].
find the pseudo-code, code explains how to read the input
int main()
{
char str[100]; // make sure that this size is enough to hold the single line
int no_line=1;
while(gets(str) != NULL && strcmp(str,"END"))
{
if(no_line % 2 == 0)
{
/*read integer values from the string "str" using sscanf, sscanf can be called in a loop with %d untill it fails */
}
else
{
/*strore string in your variable "experiments" , before copying allocate a memory for the each entry */
}
no_line++;
}
}
The redirected file is associated with the FILE * stdin. It's already opened for you...
otherwise, you can treat it the same as any other text file, and/or use the functions that are dedicated to standard input - with the only exception that you cannot seek in the file and not retrieve the size of the input.
For the data sizes you're talking about, by far the easiest thing to do is just slurp all of the content into a buffer and work on that: you don't have to be super-stingy, just make sure that you don't overrun.
If you want to be super-stingy with memory, preallocate a 4kB buffer with malloc(), progressively read() into it from stdin, and realloc() another 4kB every time the input exceeds what you've already read. If you don't care so much about being stingy with memory (e.g. on a modern machine with gigabytes of memory), just malloc() something much bigger than the expected input (e.g. a megabyte) and bug out if the input is more than that: this is far simpler to implement but less general/elegant.
You then have all of the input in a buffer and you can do what you like with it, which depends too strongly on the format of the input for me to say how you should approach that part.

c programming copying files

Having few issues with my copy program which creates a copy of a file user enteres. I decided not to use (size_t) structure instead just assigned (int) and (char) types variables so I know exact value of bytes to read() out. ie I know start at beggining of file and read 4 bytes(int) to get value of lenght of filename, which I use as size in next read()
So, when I am writing (copying file exactly with same name) users inputted file to the output file (copied file) I writing it in long string, without spaces obviously just to make it readable here,
filenamesize filename filecontentsize filecontent
ie 10 myfile.txt 5 hello
So when come to reading that data out I start at begining of file using lseek() and I know the first 4 bytes are (int) which is lenght of filename so I put that into value int namelen using the read function.
My problem is I want to use that value read for the filenamesize(first 4 bytes) to declare my array to store filename with the right lenght. How do I put this array into read() so the read stores value inside that char array specified, see below please
int namelen; //value read from first 4 bytes of file lenght of filename to go in nxt read()
char filename[namelen];
read(fd, filename[namelen], namelen);//filename should have 'myfile.txt' if user entered that filename
So my question is once I read that first 4 bytes from file giving me lenght of filename stored in namelen, I then want to read namelen amount of bytes to give me the filename of originally file so I can create copied file inside directory?
Thanks
int namelen; //value read from first 4 bytes of file lenght of filename to go in nxt read()
char* filename = new char[namelen+1];
read(fd, filename, namelen);
filename[namelen]=0; // Just to keep readed buffer c-string compatible
do something with filename
delete[] filename;
In your previous question here, you did not upvote a single answer or accept any of them. You do appear to have used those answers though.
People who answered that earlier question might be inclined to help you here if you could be bothered to show a little gratitude for their earlier help by upvoting their answers and accepting the one that you found most helpful.

How to read till end of file in MATLAB?

I have a file a.txt:
03,17.406199
05,14.580129
07,13.904058
11,14.685388
15,14.062603
20,14.364573
25,18.035175
30,21.681789
50,22.662820
The number of rows in the file are not known. I want to read the file and store
3
5
7
11
15
20
30
50
in one array and the float values in another.
How do I read in a file when the length of data is not known?
If the number of entries is the same in every row, and if all the entries are numeric, then
you can simply do
a = load('a.txt');
a will be a matrix with two columns.
Read line-by-line until you hit the EOF marker.
Certain functions (like TEXTSCAN) will continue recycling the format string until the end of the file is reached. Other functions (like FSCANF) can take Inf as a size option, indicating that it should continue reading until the end of the file. If you are reading data line-by-line in a loop, you can use the FEOF function to test if the end of the file has been reached.
Since your elements are separated by commas, take a look at csvread. This should read the entire file into a single matrix, which you can then split into the two vectors you want.
Disclaimer: not tested!
fileContents = csvread('a.txt');
integerColumn = fileContents(:, 1);
doubleColumn = fileContents(:, 2);

Resources