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.
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 does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
So I have this code:
#include <stdio.h>
#include <stdlib.h>
int functie ( int v[], int nr, int z)
{
int i,count;
scanf("%d", &z);
for(i=0;i<nr;i++) {
if(z==v[i]) {
count=count+1;
}
}
return z;
}
int main()
{
int i,nr,z;
fscanf("%d", &z);
FILE *f;
FILE *g;
f=fopen("data-in.txt", "r");
fscanf(f,"%d",&nr);
int *v=malloc(nr*sizeof(int));
for(i=0;i<nr;i++) {
fscanf(f,"%d",&v[i]);
}
g=fopen("data-out.txt", "w");
fprintf(g,"%d %d", functie(v,nr,z));
fclose(f);
fclose(g);
free(v);
}
and before I had int z=0; instead of trying to scanf my var z.
When I run this I get a stopped working error.
I have an array with numbers (integers) read from file, first line is the number of elements and second line the elements.
I need a var lets say z to check how many times an element appears in vector (check if scanned number z is equal to an element and +1 count )
example:
in file
4 (cuz I have 4 elements )
1 2 3 3 ( my elements )
than scan z as 3
z==3 true
count=1
again
count=2
Two issues here, both in main. First:
fscanf("%d", &z);
This function expects a FILE * for the first argument, which you didn't specify. Presumably you wanted to read from the console instead, so use scanf:
scanf("%d", &z);
Second issue:
fprintf(g,"%d %d", functie(v,nr,z));
Your format string is expecting two integer arguments, but you're only passing in one. Get rid of the extra format specifier:
fprintf(g,"%d", functie(v,nr,z));
fscanf will not be delimited by newlines. Best thing to do is eat through file a line at a time with fgets. So, add a line buffer to the top of main:
char line[16]; // assuming integers will actually be small
After opening your file as above with 'f':
if (fgets(line, sizeof(line), f))
{
int count = atoi(line);
int *v = (int *) malloc(count * sizeof(int));
for (int i = 0; i < count && fgets(line, sizeof(line), f); ++i)
{
v[i] = atoi(line);
}
}
You should absolutely add error checking to the above, which is minimal and for concept only (e.g. guard against bad input, buffer overflow, exceptions, count being wrong leaving you uninitialized integers at the end of the array, etc.) as this will only work if your input file is perfect. Note that 16 is generally a ridiculously small length for a line buffer. Also only do your logic against your vector if (a) the file opens, and (b) passes the first test, which is an integral number of entries.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Question 1.
#include <stdio.h>
int main(void)
{
int c;
while((c=getchar())!='\0')
{
putchar(c);
}
}
Input
Hello C.
Tell me about you.
Output
Hello C.
Tell me about you.
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
and it continues with status-time limit exceeded.
Question 2.
#include <stdio.h>
int main(void)
{
float a;
a=46.43253;
printf("\n%d",a);
printf("\n%f",a);
return 0;
}
Output
536870912
46.432529
Output- 536870912
46.432529
In general using incorrect format specifier triggers undefined behavior - which is what you have when you use %d in printf for printing float. In this case, you can expect any output usually.
However, it may also be the case that since you have specified to read the float number as integer (e.g. by using %d specifier), it simply interpreted the result as integer - hence the strange number (since floats and integers are stored differently).
If you are interested why the second printf prints a number slightly different from yours, this may help you.
This block is fine:
float a;
a=46.43253;
This block is also fine:
printf("\n%f",a);
The problem is with this block:
printf("\n%d",a);
Particularly this part:
"\n%d"
Please keep in mind you declared a float and using the integer syntax to output it. That's why you are getting the negative output
If it is a case where you don't want to change the "%d," then simply cast it as a float before output
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 7 years ago.
Improve this question
Is there any possibilities to read and add two or three different integers by using single variable ( int a ) in C language?
I didn't want to use array
I'm not sure I'm getting you, but for example, if you want to add 2 16 bits integers with a single 32bit integer, you could do
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main()
{
uint32_t a;
printf("Enter number 1: ");
scanf("%hd", (uint16_t *)(&a));
printf("Enter number 2: ");
scanf("%hd", ((uint16_t *)(&a))+1);
printf("%X\n", a);
printf("Sum = %"PRIu32"\n", (uint32_t)(*(uint16_t *)(&a)) + *(((uint16_t *)(&a)) + 1));
return 0;
}
The logic is to think about variable equals to arrays of bytes, and that's it.
This implementation still have problems that are well explained HERE
No. Every time you you atribute a new value to the same variable it replaces the old one. If you don't want to use an array and it's a simple code to add numbers, just declare three variables and atribute each value to one of them.
I do not know if you would like this, but another way you can do this will be to accept inputs like you punch in calculators, and parse to int before applying the operations on them.
Something like this
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer[256];
char * pch;
printf("input your numbers in this format ${number1}+${number2}...: ");
fgets (buffer, 256, stdin);
int sum = 0;
pch = strtok (buffer, "+");
while (pch != NULL)
{
sum += atoi (pch);
pch = strtok (NULL, "+");
}
printf("the sum is %\n", sum);
return 0;
}
so, run it and input 2+2+2 and it does the calculation for you. thanks
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need a function that gets input in the form of int1, int2, ..., intn.
I neeed to store the values of these integers in an array. A separate function is used to get the number of integers to be read. How can I make the two functions work?
If it's not clear, it's something like this:
function1 gets an integer to get the number of input to be read. Then the function2 will read that input plus one but the input must be in a single line and must be separated by a comma and/or a white space.
Function1 gets, for example 5. function2 will want to read input like: 3, 21, 5, 1, 5, 2 and store it into a separate array for later use.
Can anyone help? Thanks. I thought of using loops but I remembered that the input must be in one line. Maybe scanf? With [^,]? But how do I make it work with the first function?
Try this:
#include <stdio.h>
void getInput(int sizeOfInput, int arr[]) {
int i = 0;
printf("IN");
for(; i < sizeOfInput - 1; ++i) {
scanf("%d, ", &arr[i]);
}
scanf("%d", &arr[i]);
printf("OUT");
}
main(){
int sizeOfInput = 0;
printf("Enter how many numbers do you want to enter?");
scanf("%d", &sizeOfInput);
int arr[sizeOfInput];
getInput(sizeOfInput, arr);
}
Sorry I am lazy but for you to learn it would be the best to figure out what this code does before you use it, that is also a reason why I did not comment it.