I have an assignment where I need to get Values of RLC circuits from a file and calculate the resonant frequency however my issue is when I use the fscanf function it reads only the first line of the file and the rest comes out as zeros .
#include <stdio.h>
data
int h;
typedef struct cct
{
int code[50];
float R[50];
float L[50];
float C[50];
} CCT;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);
}
int main()
{
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
cct[i].L[i], cct[i].C[i]);
scanf("%d",&h);
fclose(fp);
}
and this is the data file
1,4.36,2.23e-2,4.65e-8
2,4.57,2.01e-2,5.00e-8
3,3.99,2.46e-2,4.82e-8
4,4.09,2.60e-2,4.70e-8
I would appreciate if someone could point put why it only gets the first line. Thanks
CCT is composed of multiple arrays (you have arrays of arrays, which is wrong for the exercise, but that's not the point) and you always write to the element zero of the arrays. For example, cct[n_p].code in fscanf() is the address of the array, which is identical to the address of cct[n_p].code[0]. Then you print code[i] in the output loop, which is blank except for i == 0.
fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);
Something like the following, perhaps
#include <stdio.h>
typedef struct cct {
int code;
float R;
float L;
float C;
} CCT;
int h;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
fclose(fp);
}
Related
As I was trying to write code which is supposed to sort some structures in a file by a specific field (key), I noticed that my function won't read the key correctly. I don't have any idea what I am doing wrong. The code is not complete.
The constr function is supposed to read one structure at a time from the binary file, then only save the varsta array. However, if I try to see what value I obtained, the values are not the ones I gave.
This is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char nume[20];
char prenume[20];
float varsta;
} PERS;
typedef struct
{
float key;
int nr;
}INDEX;
int constr(FILE *f, INDEX tabl[])
{
int n;
n = ftell(f) / sizeof(PERS);
int i, depl = 0;
PERS p;
for (i = 0; i < n; i++)
{
fseek(f, depl, 0);
fread(&p, sizeof(p), 1, f);
tabl[i].key = p.varsta;
tabl[i].nr = i;
depl += sizeof(PERS);
}
return n;
}
int main()
{
FILE *f;
PERS pers[3];
if ((f = fopen("fis.txt", "wb+")) == NULL)
{
printf("Not ok");
exit(1);
}
int i;
for (i = 0; i < 3; i++)
{
scanf("%s%s%f", &pers[i].nume, &pers[i].prenume, &pers[i].varsta);
fwrite(&pers[i], sizeof(PERS), 1, f);
}
INDEX tabl[3];
int n = constr(f, tabl);
printf("%d", tabl[2].key); //only to check if the key is correct
fclose(f);
}
The key field is a float, but you are trying to print an integer.
Change the penultimate line in your code to
printf("%.2f\n", tabl[2].key);
i keep getting a segmentation fault when running this program. I'm attempting to read the files (inserted into the command line), and allocate the x and y coordinates in each file to a dynamically allocated memory struct called POINTS (using the function called readPoints). After they have been saved into these structs, i then pass them to the function calls calc where the x and y values are multiplied, and then added onto the next x and y multiplied.. so on. Could someone please explain to me where i went wrong! I am not great at pointers.
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
float xcord;
float ycord;
}POINTS;
int readPoints(char* file, int numofpoints);
int calc(POINTS* points, int numofpoints);
int main(int argc, char* argv[])
{
int numoffiles;
FILE* file;
int result, i;
numoffiles = argc;
POINTS* pointer;
int numofpoints;
if(numoffiles == 1)
{
printf("Please enter a file\n");
}
for(i=1; i<numoffiles; i++)
{
file = fopen(argv[i], "r");
fscanf(file, "%d", &numofpoints);
pointer = readPoints(file, numofpoints);
if( pointer == NULL)
{
printf("Error return from readPoints function");
}
result = calc(&pointer[i], numoffiles);
printf("%12f", result);
free(pointer);
}
}
int readPoints(char* file,int numofpoints)
{
int i, j;
POINTS* Pointstructs;
Pointstructs = (POINTS*)malloc((numofpoints)*sizeof(POINTS));
if(file == NULL)
{
printf("Error transferring file into readPoints\n");
}
for(i=0; i<numofpoints; i++)
{
fscanf(*file, "%f, %f", &Pointstructs[i].xcord, &Pointstructs[i].ycord);
printf("%f, %f", Pointstructs[i].xcord, Pointstructs[i].ycord);
}
return Pointstructs;
}
int calc(POINTS* points, int numofpoints)
{
int i=0, j=0;
int answer;
while(i<numofpoints && j<numofpoints)
{
answer += points[i].xcord * points[j].ycord;
i++;
j++;
}
return answer;
}
readpoints functions should take its first argument as file pointer BCS fopen returns FILE pointer but u are using char pointer. fscanf first argument should be a file pointer. Pls correct it
My task is to read from two files both containing floats. Then I have to put them in a new file in an ascending order. The code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int numLines(const char * fileName){
FILE *file=fopen(fileName,"r");
int lines=0;
char c;
while((c=fgetc(file))!=EOF){
if(c==10){
lines++;
}
}
fclose(file);
return lines;
}
float * fileToArray(const char * fileName){
FILE *file=fopen(fileName,"r");
int numOfLines= numLines(fileName);
float * arr= (float*)malloc(numOfLines*sizeof(float));
int i;
for(i=0;i<numOfLines;i++){
fscanf(file,"%f\n",&arr[i]);
}
fclose(file);
return arr;
}
int cmpfunc(const void *a, const void *b){
float fa= *(const float*) a;
float fb= *(const float*) b;
return (fa>fb)-(fa<fb);
}
int isSorted(FILE *fp){
float prev;
float o;
do{
fscanf(fp,"%f\n",&prev);
fscanf(fp,"%f\n",&o);
if(prev>o){
fclose(fp);
return 1;
}
}while(fscanf(fp,"%f\n",&o)==1);
fclose(fp);
return 0;
}
int main(int argc, const char * argv[]){
const char *fileName1;
const char *fileName2;
const char *fileOut;
FILE *fp1;
FILE *fp2;
FILE *fp3;
float *arr1;
float *arr2;
int size1;
int size2;
if(argc!=4){
printf("Usage: fileSort.exe FILENAME1 FILENAME2 FILEOUT");
return 0;
}
else{
fileName1= argv[1];
fileName2= argv[2];
fileOut= argv[3];
fp1= fopen(fileName1,"r");
fp2= fopen(fileName2, "r");
fp3= fopen(fileOut, "w");
if(fp1!=NULL && fp2!=NULL){
arr1=fileToArray(fileName1);
arr2=fileToArray(fileName2);
size1=sizeof(arr1)/sizeof(float);
size2=sizeof(arr2)/sizeof(float);
if(!isSorted(fp1) || !isSorted(fp2)){
printf("The files are not sorted in increasing order. Please sort them.");
}
else{
float * arr3= malloc((size1+size2)*sizeof(float));
int k;
memcpy(arr3,arr1,size1*sizeof(float));
memcpy(arr3+size1,arr2,size2*sizeof(float));
qsort(arr3,size1+size2,sizeof(float),cmpfunc);
for(k=0;k<(size1+size2);k++){
fprintf(fp3,"%f\n",arr3[k]);
}
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
else{
printf("Files could not be opened\n");
}
return EXIT_SUCCESS;
}
Two sample files for testing this code would be:
data1.txt:
0.586399
0.769484
0.864755
6.229683
data2.txt:
0.279828
0.309235
0.591884
0.962811
1.361349
10.203892
12.158343
The result should be their ordered combination. However, I get this as a result:
0.279828
0.309235
0.586399
0.769484
No matter what I change, it always writes four numbers into the resulting file. The helper functions seem to be doing their jobs just fine. It looks like the problem comes up when I'm trying to create the third array and fill it up (or at least I assume that's the source). I have no idea where this problem is coming from though. I would really appreciate some help on this issue.
The variable arr1 is not an array, it is a pointer to a float even though you are using it as pointer to the first float element in the array.
This means that sizeof will return to you the size of the pointer which is either 4 bytes or 8 bytes depending whether you are compiler 32-bit or 64-bit.
One way to fix this is to pull out the calculation of the number of lines like this:
int size1 = numLines(fileName1);
int size2 = numLines(fileName2);
arr1=fileToArray(fileName1, size1);
arr2=fileToArray(fileName2, size2);
I created two structs to store values in.
struct pair {
int x_pos;
int y_pos;
};
struct coordinates_header {
int length;
struct pair data[1000];
};
typedef struct coordinates_header coordinates;
coordinates *coords;
I then try to store data from a file using
char line[max_read];
int x, y;
FILE *in_file = fopen(filename, "r");
int i = 0;
coordinates *new = (coordinates *)coords;
while (fgets(line,max_read,in_file) != NULL) {
sscanf(line,"%d %d", &x, &y);
new -> data[i].x_pos = x;
new -> data[i].y_pos = y;
i++;
}
new -> length = i;
Then I try to print out the values
int print_struct(void *coords) {
coordinates *new = (coordinates *)coords;
for (int i = 0; i < new -> length; i++) {
printf("%d, %d\n", new->data[i].x_pos, new->data[i].y_pos);
}
return 0;
}
And then I get a segmentation fault
I was wondering if someone could point out where the error is. I have no experience with void but require the flexibility for the structure in some functions I'm going to use.
The file read will have the form
100 30
50 200
.. ..
I believe their are some mistakes in your code:
Instead of using coordinates *coords;, which is just a dangling pointer not pointing anywhere in memory, you should just declare a structure member coordinates coords.
Their is no need for void* pointers in your code. You would be better off using coordinates *coords to access the address of the structure member coordinates coords, instead of void *coords.
You are not checking the return value of FILE *in_file, which could return NULL if not opened properly.
It is always good to check the result of sscanf(), just incase two x and y coordinates were not found on a line.
With these recommendations, you can write your code like this:
#include <stdio.h>
#include <stdlib.h>
#define NUMCOORDS 1000
#define MAXREAD 100
typedef struct {
int x_pos;
int y_pos;
} coords_t;
typedef struct {
coords_t coords[NUMCOORDS];
int length;
} coordinates_t;
void print_struct(coordinates_t *coordinates);
int main(void) {
coordinates_t coordinates;
char line[MAXREAD];
FILE *in_file;
int i = 0;
in_file = fopen("coords.txt", "r");
if (in_file == NULL) {
fprintf(stderr, "Error reading file.\n");
exit(EXIT_FAILURE);
}
while (fgets(line, MAXREAD, in_file) != NULL) {
if (sscanf(line, "%d %d", &coordinates.coords[i].x_pos,
&coordinates.coords[i].y_pos) != 2) {
fprintf(stderr, "two coordinates(x, y) not found.\n");
exit(EXIT_FAILURE);
}
i++;
}
coordinates.length = i;
print_struct(&coordinates);
fclose(in_file);
return 0;
}
void print_struct(coordinates_t *coordinates) {
int i;
for (i = 0; i < coordinates->length; i++) {
printf("%d, %d\n", coordinates->coords[i].x_pos, coordinates->coords[i].y_pos);
}
}
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char* name;
float weight;
} Person;
int main()
{
Person *person=malloc(10*sizeof(Person));
int i=0;
char row[20];
FILE *input=fopen("input.txt","r+");
while(fscanf( input, "%s", &row)>0) i++;
i/=5;
printf("%d\n", i);
fseek(input,0,SEEK_SET);
int j;
char string[20];
for (j=0;j<i;j++){
fscanf(input,"%s",string);
fscanf(input,"ID:%d",&person[j].id);
fscanf(input,"Name:%s",person[j].name);
fscanf(input,"Weight:%f",&person[j].weight);
fscanf(input,"%s",string);
}
fclose(input);
//Person:{
//ID:1214124141
//Name:Trump
//Weight:101.50
//}
//Person:{
//ID:5235252525
//Name:Obama
//Weight:78.30
//}
return 0;
}
Hello!
I want to read a structure from a file, but my array person contains only 0 even after I read from the file. My input file has the structure shown in the comment lines.
What am I not doing well?
Thanks a lot for the help!
fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long long int id;//32bit int can't hold like 5235252525
char name[20];//Allocate space
float weight;
} Person;
#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"
int main(void){
FILE *input=fopen("input.txt", "r+");
if(!input){
perror("fopen");
return -1;
}
int n = 0;
Person p;
while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
++n;
printf("number of record: %d\n", n);
Person *person = malloc(n * sizeof(Person));
if(!person){
perror("malloc");
fclose(input);
return -2;
}
rewind(input);
for (int i = 0; i < n; ++i){
fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
}
fclose(input);
//check print
for (int i = 0; i < n; ++i){
printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
}
free(person);
return 0;
}