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.
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 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 5 years ago.
Improve this question
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main ()
{
FILE *fp;
int r, i;
char fp_string [600] = "num1000.bin";
fp = fopen(fp_string, "rb");
for (i=0;i<1000;i++)
{
fread(&r, sizeof(int), 1, fp);
printf("%d, ", r);
}
fclose(fp);
getch();
return 0;
}
This code currently reads and displays a binary file called num1000.bin, which contains 1000 random numbers. This code uses a for loop. How can I perform the exact same task but instead using an array?
To define an array:
int r[1000];
To read 1000 files from your file, use fread:
fread(r, sizeof(int), 1000, fp);
As you can see in the description of the fread function, one of its parameters specifies how many elements to read. Change it from 1 to 1000.
To display your numbers, you still need a loop.
for (i=0;i<1000;i++)
{
printf("%d, ", r[i]);
}
Notice how it's now r[i] - because r is now an array that contains 1000 numbers, and not just one.
Firslty you need to know the format of the random numbers. Presumably they are in native int format, but you need to check, especially since they are rnadom and so no commonsense testing is possible.
If you know that the number is exactly 1000, you can read in using fread
int r[1000];
fread(r, sizeof(int), 1000, fp);
But this is a bad habit. The data might end early. The format might be endian-reversed from native, or 16 or 64 bit instead of 32. You really need to get into the habit of reading binary data portably.
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 6 years ago.
Improve this question
SOLVED BELOW
I'm writing an IP forwarding program and I'm trying to read the header data.
I have structs for different lines such as this for the first line:
struct line1 {
char a; //version
char b; //header length
unsigned short c; //datagram length
};
The different data types are dependent on the length of the data field.
I have variable initialization:
struct line1 l1 = {};
FILE *ip_packets, *routing_table;
My professor showed a simple read function that was something like read(ip_packets, 4, l1) (4 Bytes) that automatically put the data into the struct fields. I have searched around the web and haven't found a simple method like this. What read function am I looking for?
I've tried fscanf in this way:
if (fscanf(ip_packets, "%c %c %hu", &l1.a, &l1.b, &l1.c)){
printf("%c\n", l1.a);
printf("%c\n", l1.b);
printf("%hu\n", l1.c);
}
I've also tried syntaxt %c,%c,%hu or %c/%c/%hu
but that just prints:
Kendalls-Mac-mini:Programming 2 kendallweihe$ ./ip_read
E
0
SOLUTION
Turns out I was reading it in correctly, but I needed to print the integer value. My testing verification is in terms of integers. Easy enough.
BETTER SOLUTION
fread(&l1, 4, 1, ip_packets);
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 6 years ago.
Improve this question
I have the following kind of source code in C++. Now I want to make this program in C too (with C++ compiler) but I am confused about allocation.
My current code of my function
char* product(char* a, unsigned short b, unsigned short zeroes)
{
char* finish = new char[strlen(a) + 2 + zeroes]();
short carry = 0;
unsigned short c;
unsigned short s;
for (short i = strlen(a) - 1; i >= 0; i--) {
c = char2int(a[i]);
s = (b*c + carry);
carry = s / 10;
finish[strlen(finish)] = int2char(s % 10);
}
printf("%s", finish); // dump! Looking what is inside
if (carry > 0) {
finish[strlen(finish)] = int2char(carry);
}
reverseChar(finish);
for (short i = 0; i < zeroes; i++) {
finish[strlen(finish)] = '0';
}
return ltrim(finish,'0'); // trim
}
I've tried to allocate via malloc.h using this (char*) malloc (strlen(a) + 2 + zeroes) but it gave me random chars (at the dump part). Is someone possible to say me what just happend here?
The operator new allocates memory, but also calls the constructors of the objects to be created.
In this case char() which initializes them to zero.
To have equvalent code you could for example use memset.
Note that if your type is not of size one (like char), you also have to multiply the amount you give to malloc by the size of the type. new does this automatically.
The actual issue with your code starts when you call strlen(finish) when there is garbage in the memory.
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 8 years ago.
Improve this question
The program is suppose to convert binary number to decimal form. Only using scanf() and printf() library functions. Takes in a char array from user ---no prompt outputs decimal form, function must be used with parameter (char binaryString[]) after conversion result must be printed out in main. Program does not work don't think I'm converting the binary form to decimal form correctly in function binaryToDecimal since i cant use pow() I'm lost
#include <stdio.h>
#include <math.h>
int binaryToDecimal(char binaryString[]) {
int c, j = 1, decimalNumber = 0;
for (binaryString[c = 0]; binaryString[c] > binaryString[33];
binaryString[++c]) {
while (binaryString[c] != 0) {
remainder = binaryString[c] % 10;
decimalNumber = decimalNumber + remainder * j;
j = j * 2;
binaryString[c] = binaryString[c] / 10;
}
}
return decimalNumber;
}
int binaryToDecimalMain() {
int arraysize = 33;
char binaryString[arraysize];
scanf("%32s", binaryString);
printf("%d",binaryToDecimal(binaryString []);
return 0;
}
I not give you the algorithm because it's seems that you are learning how to program and it is important to you to learn to discover how to solve the problems that are given to you.But I can give you some hints:
use binaryString only to compare with '0' or '1'. Don't try to make any operations like '%' on it.
iterate on the binaryString character by character (no while inside for [this is only for this case, there some algorithm that is necessary to do something like this])
your logic to convert is on the right track
Also you should call your main function main.