Storing values from a file into an array with malloc - c
for an assignment I am meant to store values from a file into an array using malloc. The code compiles but stays stuck in the terminal when I execute it. I thought that i was not storing the value from the file but that is working fine. I think I'm using the array incorrectly.
Thank you.
#include <stdio.h>
#include <stdlib.h>
int main(void){
double* arrayPtr = malloc( 10* sizeof(double));
char lines[128]; //the lines of the txt file
int i;
FILE* file;
file = fopen("TriData1.txt", "r");
int count = 0;
while (fgets(lines, 128, file))
{
scanf(lines, "%d", &i);
scanf(" %le", &arrayPtr[i]);
printf(" %d\n", i);
printf("line %d: %f\n", (count + 1), arrayPtr[count])
count++;
}
free(arrayPtr);
return 0;
}
Related
Getting data from a .txt file in C
I'm new to C and I have to read data from a file, and I need to store that data in an array. I'm using FILE *fptr; fptr = fopen(¨filename.txt¨, ¨r¨) to read and fscanf(fptr,"%d", &num); to get the file data, however when compiling I only seem to get the memory location for it (I think? the file I'm using to try the code out has the number 5368 and I'm getting 6422296) int main(void) { FILE *fptr; fptr = fopen("example.txt" , "r"); if ((fptr = fopen("example.txt","r")) == NULL) { printf("Error! opening file"); exit(1); } int num; fscanf(fptr,"%d", &num); printf("VALUE OF NUM IS %d", &num); fclose(fptr); return 0; }
Here a minimal example demonstrating reading a couple of numbers from filename.txt into an array num. You need to add error handling, and if you cannot fix the size (LEN) then either calculate it by figuring out how numbers is in the file, or realloc the size of the num array as needed: #include <stdio.h> #define LEN 2 int main() { FILE *fptr = fopen("./filename.txt", "r"); int num[LEN]; for(int i = 0; i < LEN; i++) { fscanf(fptr, "%d", num + i); printf("%d\n", num[i]); } fclose(fptr); }
Struct fscanf in file C
In file I need to read some inputs: this is an example: 8 15 [1,1] v=5 s=4#o [4,2] v=1 s=9#x typedef struct{ int red2; int stupac2; int visina; int sirina; char boja[10]; }Tunel; FILE* fin = fopen("farbanje.txt", "r"); Tunel* tuneli = malloc(sizeof(Tunel)*50); // if(fin!=0) fscanf(fin,"%d %d", &r,&s); printf("%d %d", r,s); int p=0; while (fscanf(fin, "[%d,%d]", &tuneli[p].red2, &tuneli[p].stupac2) == 2) { p++; } for(i=0;i<p;i++) { printf("[%d,%d]", tuneli[i].red2, tuneli[i].stupac2); } Problem is that it wont read me properly inputs from here: [1,1] v=5 s=4#o Last line where i use printf shows some random numbers.
Agree it is better to use fgets But if you want to continue to use your current approach, #include <stdio.h> #include <stdlib.h> typedef struct{ int red2; int stupac2; int visina; int sirina; char boja[10]; }Tunel; int main(){ int r, s, i; FILE*fin=fopen("farbanje.txt", "r"); if(fin==NULL) { printf("error reading file\n"); return 1; } Tunel *tuneli=(Tunel*)malloc(sizeof(Tunel)*50); fscanf(fin,"%d %d\n", &r,&s); printf("%d %d", r,s); int p=0; while (fscanf(fin, " [%d,%d]%*[^\n]", &tuneli[p].red2, &tuneli[p].stupac2) == 2) { p++; } fclose(fin); for(i=0;i<p;i++) { printf("[%d,%d]", tuneli[i].red2, tuneli[i].stupac2); } }
Last line where i use printf shows some random numbers.... The random numbers you see are because the buffers to print were not properly populated yet. This example shows how to read the file, using fgets() to read a line buffer, then use sscanf() to parse the first two values from the lines. (read in-code comments for a few other tips.) int main(void)//minimum signature for main includes 'void' { int r = 0; int s = 0; char line[80] = {0};//{initializer for arrays} int p = 0; Tunel *tuneli = malloc(sizeof(*tuneli)*50); if(tuneli)//always test return of malloc before using it { FILE *fin = fopen(".\\farbanje.txt", "r"); if(fin)//always test return of fopen before using it { fgets(line, sizeof(line), fin); sscanf(line, "%d %d", &r, &s); while(fgets(line, sizeof(line), fin)) { sscanf(line, " [%d,%d]", &tuneli[p].red2, &tuneli[p].stupac2); //note space ^ here to read only visible characters printf("[%d,%d]\n", tuneli[p].red2, tuneli[p].stupac2);//content is now populated corretly p++; } fclose(fin);//close when finished } free(tuneli);//free when done to prevent memory leaks } return 0; }
Finding Total Memory in Bytes in C
In my assignment I am expected that Print the total memory in bytes required for the dynamic array I have to read the file and find required byte. And also it is not my assignment main purpose #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define N 100 //Change this acording to the size of the file. #define PATH "list.txt" int * read_array(char *filename,int *count); int main(void){ int *arr,count; arr=read_array(PATH,&count); int byte_used= count * sizeof(int); printf("%d number of byte used\n",byte_used); free(arr); } int * read_array(char *filename, int *i){ FILE *fp=fopen(filename, "rb"); if (fp==NULL){ printf("File does not exist\n"); *i=0 return 0; } int a=0,counter=1; int *arr; arr=(int*)malloc(counter*N*sizeof(int)); while(fscanf(fp,"%d,",&arr[a]) == 1){ a++; /* When all allocated memory is filed, do this */ if (counter*N<=a){ counter++; arr=(int*)realloc(arr,counter*N*sizeof(int)); } } *i=a; //returns how many numbers in this file return arr; } So I am wondering in 3rd line in main is valid for expectations or there is another way to find the usage of byte? Also I will do the same thing with using linked list. So we learning dynamic memory allocation. little example of list.txt 107557,55092,62318,70428,176047,80485,54378,196442,189223,30437,60540,192159,33269,76106,45347,157100,146714,148826,117640,101563,76183,37355,182131,177126,194497,183527,194987,38558,33858,32845,125977,63521,119818,152605,188990,76983,129104,6248,16584,166616,130089,18922,24273,156750,101204,196746,188582,120890,74983,112513,129785,77139,173710,29203,113654,65771,190139,133410,130882,120492,50775,137392,165089,105591,147175,57138,61213,112020,180819,90229,89965,90348,113128,61010,141313,6982,59301,136882,16740,35281,120563,10840,112388,72077,136377,26905,171965,101848,112372,107374,153418,113139,37599,122005,53904,101215,86164,38777,122907,16655,115439,153224,25420,193267,115505,89156,156848,137102,31725,19419,25086,105131,144132,40022,143155,99377,31892,831,139379,191996,162653,82880,170260,61363,80250,115883,117688,92847,184991,49799,122085,21224,48320,48359,119315,96627,159768,80137,93466,15103,174821,83863,129759,173513,118821,63486,77311,87648,23289,12885,39730,89500,58910,136438,118109,175974,7664,160314,98305,78389,31732,24061,160832,3729,61192,112101,129654,180326,59920,165289,58643,107106,44683,54488,175689,7988,70030,52949,89169,112724,181046,144363,56838,100020,26208,118902,197054,186915,2010,76672,194157,23433,166280,88101,85856,91119,57961,33077,198816,111023,55898,75583,58333,153127,20589,14342,61971,127062,1377,34588,131515,121206,110805,3851,172936,72173,73173,175725,21785,68748,6056,80365,24673,125787,105702,181725,175734,32495,178036,137669,63675,444,164708,191622,156968,62629,131119,84594,8586,124567,116197,75871,49064,1049,27621,108219,16135,176144,43276,198582,117926,33090,128903,70690,11719,43055,42658,46582,150291,14896,138883,44807,83779,26870,192992,183926,54984,165114,138820,139714,20630,85346,16490,96596,111548,138552,159941,48643,160220,149088,126113,173179,79943,7088,187176,36160,53923,111483,91996,38794,78371,148969,43052,56343,32518,1922,64291,23974,191324,1011,182138,197160,154265,15338,140128,76576,51349,150257,149451,5498,184812,178437,56529,179679,158530,165798,141758,84579,188457,7807,154972,51980,78319,13982,131312,143826,143181,33524,15063,81554,15272,124150,28990,168269,40077,112055,1340,90010,144856,152767,131248,59260,73587,36615,36189,167944,145935,68244,180668,35806,4456,152727,57047,120876,41564,193295,176540,168954,23092,28061,1541,58999,115210,97097,148034,54665,102469,152367,56568,145834,33905,44792,173362,16842,78441,174358,34009,174751,114538,122805,167504,179079,58505,28972,164371,136677,39996,179655,24916,199296,189433,108802,183450,136978,109015,167131,29554,12661,68967,189654,27690,45662,149812,48602,17899,130212,102263,89393,133828,178975,52897,120831,32563,95749,109746,184058,197708,140014,164609,145017,103794,98801,148181,102247,55108,128686,75497,127044,185145,66265,67860,140704,10899,114890,103232,12392,116319,180102,132965,146363,177084,191390,190615,44790,51776,31505,135222,12767,113621,40095,73462,142896,152514,
Third line in your code is enough for you, but if you want to make your code better you can something line; if( a < counter*N ) arr=(int*)realloc( arr, a*sizeof(int) );
According to the question text: Assignment: Print the total memory in bytes required for the dynamic array With that assignment you can simplify your code a lot. Something like: int getIntsRequired(char *filename) { FILE *fp = fopen(filename, "rb"); if (fp == NULL) return 0; int tmp; int counter = 0; while(fscanf(fp, "%d,", &tmp) == 1) ++counter; fclose(fp); return counter; } size_t getBytesRequired(char *filename) { return sizeof(int) * getIntsRequired(filename); } int main(void){ size_t bytes_required = getBytesRequired(YOUR_FILE_NAME); printf("%zu number of byte required\n", bytes_required); return 0; }
fscanf always returns 0(CLOSED)
I am a beginner in C programming, and I am trying to write a simple code to read a text file and write its content into an array, then print it on console. However, I always get 0.0000, and I could not solve the problem. #include <stdio.h> #include <stdlib.h> int numOfLines(FILE *fp1); void printarr(float arr[], int size); float *filetoArr(FILE *fp, int arrsize); int main(int argc, const char *argv[]) { char *fileName1 = argv[1]; FILE *fp1 = fopen(fileName1, "r"); printf("File name: %s", fileName1); int size = numOfLines(fp1); printf("Number of lines in the file: %d\n", size); float *arr = filetoArr(fp1, size); printarr(arr, size); free(arr); fclose(fp1); } void printarr(float *arr, int size) { for (int i = 0; i < size; i++) { printf("%f ", *(arr + i)); } } float *filetoArr(FILE *fp, int arrsize) { int size = arrsize; float *arr = (float *)malloc(sizeof(float) * size); for (int i = 0; i < size; i++) { fscanf(fp, "%f\n", (arr+i)); } return (arr); } int numOfLines(FILE *fp1) { int numberOfLines = 0; char c; do { c = getc(fp1); if (c == '\n') { numberOfLines++; } } while (c != EOF); return numberOfLines; }
your numOfLines goes to the end of the file. You have to rewind(fp1) to reset your file handle to position 0, or fscanf hits the end of the file, and doesn't read anything (check return code from fscanf: it should be 1 I bet you're getting 0 all the time)
There are multiple problems in your code: you read the whole file in numOfLines(): you must reset the file pointer to the beginning of file with rewind(fp1); so fscanf() can read the file instead of hitting the end of file immediately. the variable c used to read bytes from the file must be defined as an int for the test for end of file to be reliable. Otherwise, depending on whether char is signed or not by default, the EOF would never match or could potentially match the character \377 as end of file erroneously. you do not check for failure to open the file. Although returning 0 is implicit for function main() since C99, it is advisable to write the return 0; statement explicitly for better clarity.
Read comma separated numbers from a file in C
I have a problem when trying to read a file with comma separated numbers, I want to have a function that creates arrays of integers (not knowing how many parameters the array has at first) in a file like this: 1,0,3,4,5,2 3,4,2,7,4,10 1,3,0,0,1,2 and so on. The result I want is something like int v[]={1,0,3,4,5,2} for every line in the file (obviously with the values in each line) so I can add this array to a matrix. I tried using fscanf, but I can't seem to make it stop at the end of each line. I also tried fgets, strtok, and many other suggestions I found on the Internet, but I don't know how to do it! I'm using Eclipse Indigo in a 32-bit machine.
#include <stdio.h> #include <stdlib.h> int main(){ FILE *fp; int data,row,col,c,count,inc; int *array, capacity=10; char ch; array=(int*)malloc(sizeof(int)*capacity); fp=fopen("data.csv","r"); row=col=c=count=0; while(EOF!=(inc=fscanf(fp,"%d%c", &data, &ch)) && inc == 2){ ++c;//COLUMN count if(capacity==count) array=(int*)realloc(array, sizeof(int)*(capacity*=2)); array[count++] = data; if(ch == '\n'){ ++row; if(col == 0){ col = c; } else if(col != c){ fprintf(stderr, "format error of different Column of Row at %d\n", row); goto exit; } c = 0; } else if(ch != ','){ fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row); goto exit; } } { //check print int i,j; // int (*matrix)[col]=array; for(i=0;i<row;++i){ for(j=0;j<col;++j) printf("%d ", array[i*col + j]);//matrix[i][j] printf("\n"); } } exit: fclose(fp); free(array); return 0; }
With the following code you will store the CSV into a multidimensional array : /* Preprocessor directives */ #include <stdio.h> #include <stdlib.h> #define ARRAYSIZE(x) (sizeof(x)/sizeof(*(x))) const char filename[] = "file.csv"; /* * Open the file. */ FILE *file = fopen(filename, "r"); if ( file ) { int array[10][10]; size_t i, j, k; char buffer[BUFSIZ], *ptr; /* * Read each line from the file. */ for ( i = 0; fgets(buffer, sizeof buffer, file); ++i ) { /* * Parse the comma-separated values from each line into 'array'. */ for ( j = 0, ptr = buffer; j < ARRAYSIZE(*array); ++j, ++ptr ) { array[i][j] = (int)strtol(ptr, &ptr, 10); } } fclose(file);