I have a file in csv format look like this:
0.0060862,0.31869
0.025889,0.21183
0.064364,0.094135
0.10712,-0.0081176
0.15062,-0.073904
I would like to load the first column to array a and second column to array b. This is what the code looks like:
double a[5];
double b[5];
int i=0;
FILE* fileHandle = NULL;
fopen_s(&fileHandle, fileName.csv, "r+");
for(i=0;i<5;i++)
{
fscanf_s(fileHandle,"%lf,%lf",a[i],b[i]);
}
fclose(fileHandle);
Now I am converting the csv file to a binary file; the data is represented in 2's complement in unsigned int. How should I change my code?
I changed the code to
unsigned x[5];
unsigned y[5];
double a[5];
double b[5];
int i=0;
FILE* fileHandle = NULL;
fopen_s(&fileHandle, fileName.csv, "rb+");
for(i=0;i<5;i++)
{
fscanf_s(fileHandle,"%u,%u",x[i],y[i]);
a[i] = x[i]/(2^15);
b[i] = y[i]/(2^15);
}
fclose(fileHandle);
But x[i] and y[i] read from the binary is always 3435973836. How should I change my code to make it work?
When your data is binary, you don't need to convert it with fprintf and fscanf.
You can just read and write you array with fread and fwrite.
If your data alternates a and b records, you will better organize your variables the same way :
struct ab {
int a, b;
} ab[5];
and read it all in one shot with
fread(ab, sizeof (int), 10, fileHandle);
Then process it the way you like.
(see man fread, and man fwrite for details)
Related
I need to write function which will write elements of array into binary file, and after that find the mean value of elements of binary file.
#include <stdio.h>
double enterArray(){
int i=0,n;
double a[101];
FILE* fp=fopen("niz.bin", "w");
while(1){
scanf("%lf", &a[i]);
if(a[i]==-1)break;
i++;
if(i==100)break;
}
n=i;
for (i=0; i<n; i++)
fwrite(a,4, n, fp);
fclose(fp);
return 0;
}
double meanValue(){
return 1;
}
int main() {
enterArray();
printf("%g\n", meanValue());
return 0;
}
I get some random characters in niz.bin file. Could you help me fix my code?
There are a few problems with the code.
You take an arbitrary number of doubles, and then write the first n * 4 bytes in the array "repeatedly" to the file.
You don't know for sure that sizeof (double) is equal to 4 bytes.
On every iteration, you write (n * 4) bytes from the array a to the file.
What you want is, starting from i * sizeof (double), write sizeof (double) bytes to the file (if you want to use a loop. You could simply just write (n * sizeof (double) bytes to the file at once)
You use the "w" mode in fopen, which is not the "write binary" mode. Use "wb" instead.
Then, in meanValue(), you don't do anything. Writing/reading a 10-element double array to/from a binary file can be done in the following way:
/* write to the file */
double write_arr[10] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
FILE *fp = fopen("niz.bin", "wb");
fwrite(&write_arr, sizeof(double), 10, fp);
fclose(fp);
/* read from the file */
fp = fopen("niz.bin", "rb");
double read_arr[10];
fread(&read_arr, sizeof (double), 10, fp);
Also, note that you must identify how many elements you're going to write to the file, as you write the bytes in the file without knowing how many to write in advance. As you don't write the elements immediately, you could serialize the number of elements in the first 4 bytes in the file. And when you read from it, read the first 4 bytes to know how many doubles lying ahead.
I have no idea how to do this. Here is the simplified version of my code. I am supposed to read off a binary file to a 2D array.
void readf(const char *fname, int a[50][50]){
int i=0;
FILE *f;
f = fopen(fname,"rb");
fread(a[i], sizeof(int), 1, f);
}
I tried using for loops and &a and a[i][j] and I ended up with this.
The file I am trying to read is .bin file and it only contains 0s and 1s
Can some one explain me how to read content from a binary file?
I have done this:
FILE *fp;
int a[50];
fp=fopen("x.exe","rb");
while(fread(&a,sizeof(a),1,fp)==1)
{
printf("%d",a);
}
suppose that file only contain integer values.
Also I tired writing into a file using structures, and I can easily read&write contents of it, but when I try reading some other binary file I just got garbage value.
Or is it impossible to read a .exe file compliled and linked?
the correct way is:
int myreadfile(void)
{
FILE *fp;
int i, n;
unsigned char a[50];
if (!(fp=fopen("x.exe","rb"))) return(0);
while(n=fread(a,1,sizeof(a), fp))
{
for (i=0; i<n; i++)
printf("%02x ",a[i]);
printf("\n");
}
fclose(fp);
return 1;
}
Note that the buffer is of type unsigned char. That is because
a) you don't know if the file is a complete number of ints (but it is of char, i.e. bytes) and
b) in the printf call, the char will be converted to intand would the high bit of the char be a 1, it would be sign-extended, which we don't want.
Also, fread does not try to read a whole buffer but just any number of bytes still in the file (to a maximum of the buffer).
I would like to write a program in C that gets the file content via stdin and reads it line by line and, for each line, converts it to an array of 8-bit integer values.
I also would like to be able to do the reverse process. After working with my array of 8-bit values, I would like to convert it again to "lines" that would be organized as a new buffer.
So basically, I would like to convert a char * line to an int array[] and back (an int array[] to a char * line) while keeping the consistency, so when I create the file again out of the conversions, the file is valid (and by valid I mean, the conversion from int array[] to char * line generates the same content of the original char * line, while reading each line of the stdin.
My code is currently as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read;
stream = stdin;
if (stream == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, stream)) != -1) {
char * array = line_to_array(line);
// here I include the rest of my code
// where I am going to use the generated array
// ...
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}
The line_to_array function would be the one to convert the "line" content to the array of integers. In a second file, I would just do the opposite.
The mechanics of the process would be like this:
The first program (first.c) would receive a file content via stdin. By reading it using getline, I would have each line to convert to an array of integers and send each line to a second program (second.c) that would convert each array to a char * buffer again and the reconstruct the file.
In the terminal, I would run it like this:
./first | ./second
I appreciate any help on this matter.
Thank you.
I believe you may already know that a name of array is a kind of constant pointer. You could verify the fact from following code:
char hello[] = "hello world!";
for( int idx=0; *(hello + idx) != 0; idx++ )
{
printf("%c", *(hello + idx));
}
printf("\n");
So, there are no reason to convert character pointer to array. For your information, A char variable is a 8bit data in C, this can contain a integer value which is represent a character: 65 represent 'A' in ASCII code.
Secondly, this link may help you to understand how to convert between c string and std::string.
On second thought, may your input file is UNICODE or UTF-8 encoded file which is using multi-byte character code. In that case, you may not able to use getline() to read the string from the file. If so, please refer this question: Reading unicode characters.
I wish following code assist you to understand char type, array and pointer in C/C++:
std::string hello("Hello world");
const char *ptr = hello.c_str();
for( int idx=0; idx < hello.size(); idx++ )
{
printf("%3d ", *(ptr + idx));
}
printf("\n");
std::string hello("Hello world");
const char *ptr = hello.c_str();
for( int idx=0; idx < hello.size(); idx++ )
{
printf("%3d ", ptr[idx]);
}
printf("\n");
code doesnt accept values from file since when i print some garbage pops up
the file is a textfile with a letter representing a status, and theres a number. there are 5 sets of these , each on new line the letter and the number is seperated with a space, i need to get the numbers in one array
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char status;
int number;
} information;
int main() {
int array[5] = {0};
int i;
FILE *pointer = fopen("transaction22.txt", "r");
information information1;
for (i = 0; i < 5; i++) {
fread(&information1, sizeof(information1), 1, pointer);
array[i] = information1.number;
printf("%d", information1.number);
}
return 0;
}
You can use fscanf instead of fread as:
fscanf(pointer, "%s %d", info1.status, &info1.number);
where status will be defined as char status[2]; inside struct information.
fread is used for reading raw bytes (blocks of data) from a file.
Now, you are using a text file and trying to read sizeof(info) amount of data which is 5 bytes of data (assuming 32-bit int), therefore what you get after first fread is:
info1.status (1 byte) info1.number (4 bytes)
Byte 1 SPACE + number + NEWLINE + [One more byte]
read by fread (next four bytes read by fread)
Thus info1.number is storing a garbage value.
Also the successive fread call starts reading after the data read by previous fread.
Better to use a character array like c[5]. and replace this is with struct. variable in fread ..like in for loop
fread(c,sizeof(c),1,pointer)
than use
print("%s\n",c);