How to Read Integers From a File in C and Sum Them
-
02-03-2018 #ane
Registered User
Read integers from a file
Hello,
I am trying to read integer from a .txt file and then shop the integers in the allocated array using malloc(). My thought is every bit following:
Code:
int *read_text(char *fp, int *size); FILE *fp; fp=fopen("/Users/HughNguyen/Google Bulldoze/Notability/CSCI 2021 Lab/Project1/information/short.txt", "r"); char* array; int i, count = 0; array = malloc(len*sizeof(char)); if (fp == NULL){ size = -one; return NULL; } else{ while(!feof(fp)){ fscanf(file, "%d", &array[count]); count++; } } for(i=0; i<count; i++){ printf(" \n a[%d] = %d\due north",i,assortment[i]); } rewind(fp); fclose(fp); return 0;
Hither is my reason:- I open the file using fopen() and I become through the file by using fscanf() to count the number of integers in my file. Then I used malloc() to allocate an array of proper size.
- I want to use rewind() office to become back to the outset of the file and so reads integers into my array. Shut the file when I am done reading all ints. I take to return a pointer to the allocated array.
- The statement "size" in "int *read_text( char *fp, int *size)" indicates a pointer to an integer which is set to the length of the allocated array. I want to gear up upward a condition that if my file cannot exist opened using fopen(), then will fix my size to -1 and return Zero.
- This is a role of the whole program. There are 3 parts: text_main text_main.c read_text.c.
I have some errors such as:- Redefinition of 'fp' with a different type: 'int' vs 'FILE *'
- Use of undeclared identifier 'size'
- A parameter list without types is but allowed in a function definition
How tin can I navigate these errors?
Any tip will exist greatly appreciated. Thank you!
-
02-03-2018 #2
Lurking
As for your errors, can yous explain what these parameters are for?
> int *read_text(char *fp, int *size);
Why is the first named fp? That seems to be 1 problem.
And why oasis't y'all used size?Well, anyway, to read a file of integers, I think the simplest lawmaking is something like this:
Code:
int *array = malloc( (?) * sizeof(*array)); if (array == NULL) { perror("malloc"); // or whatsoever other mistake handling code return EXIT_FAILURE; } for (int i = 0; i < count; i++) { fscanf(fp, "%d", &assortment[i]); }
Code:
while ( (rv = fscanf(fp, "%*d")) > 0) count++;
For this reason I call back information technology is much easier to brand a guess at the size of the array that you need, and if you know how, embiggen the array as you read.
Lawmaking:
size_t cap = fifteen, size = 0; void *temp = Goose egg; int *array = malloc(cap * sizeof(*array)); while (fscanf(fp, "%d", &array[size]) == 1) { size++; if (size == cap) { cap *= 2; temp = realloc(assortment, cap * sizeof(*array)); if (temp == NULL) { perror("realloc"); free(temp); return EXIT_FAILURE; } array = temp; } }
-
02-03-2018 #3
Registered User
Howdy WhiteFlags,
Give thanks y'all for your response. I am happy to explain myself.
- Get-go, my bad for picking the proper name. I should have named fp as "fname" as in "file name".
- I recollect I did use size as in: char* assortment = malloc(*size*sizeof(char));
- How do yous put your code in the fashion in your post? Information technology looks so cool!
- There are certain means to do this input style, but I demand to stick to the this open up source project claiming instructions.
Code:
int *read_text_deltas(char *fname, int *len){ FILE *fname = fopen("text.txt", "r"); int i, count = 0; char* array = malloc(*len*sizeof(char)); if (fname == NULL){ len = -1; return Nada; } else{ while(!feof(fname)){ fscanf(fname, "%d", &array[count]); count++; } } for(i=0; i<count; i++){ printf(" \n a[%d] = %d\due north",i,assortment[i]); } rewind(fname); fclose(fname); return 0; }
-
02-03-2018 #iv
Lurking
- Ah okay, are you lot sure that yous didn't hateful something similar this instead?
Code:
FILE *fp = fopen(fname, "r");
You go along renaming your file variable the same as your string!
- Okay, well, little things matter. In the original code, there was int *size, and you used len (a non-pointer with the wrong proper noun).
- I post code in [code][/lawmaking] tags like everyone else. If your source has no other formatting, the syntax would be highlighted for you lot too.
I'm yet uncertain, just you might want to practise something like this.
Code:
count = *len; assortment = malloc(count * sizeof(*assortment));
Also, is at that place a reason you alleged the array every bit a char*? Since we're reading integers with "%d", it's appropriate to use int, not char.
- Ah okay, are you lot sure that yous didn't hateful something similar this instead?
-
02-03-2018 #5
Registered User
So actually, fname will stand for for whatever the proper noun of the file I am going to pass in the function fopen() right?
In my text_main.c, I have:
Code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "deltas.h" int main(int argc, char *argv[]){ if(argc < three){ printf("usage: %south <format> <filename>\n",argv[0]); printf(" <format> is one of\due north"); printf(" text : text ints are in the given filename\north"); printf(" int : binary ints are in the given filename\n"); printf(" 4bit : 4bit binary ints are in the given filename\n"); return 1; } char *format = argv[ane]; char *fname = argv[2]; int data_len = -one; int *data_vals = Nada; if( strcmp("text", format)==0 ){ printf("Reading text format\north"); data_vals = read_text_deltas(fname, &data_len); } else if( strcmp("int", format)==0 ){ printf("Reading binary int format\due north"); data_vals = read_int_deltas(fname, &data_len); } else if( strcmp("4bit", format)==0 ){ printf("Reading 4bit binary int format\n"); data_vals = read_4bit_deltas(fname, &data_len); } else{ printf("Unknown format '%s'\northward",format); return ane; } printf("data_len: %d\n",data_len); printf("%4s %4s\northward","#","read"); for(int i=0; i<data_len; i++){ printf("%4d %4d\north",i,data_vals[i]); } costless(data_vals); return 0; }
You are correct about my array declaration. I must use int.
Now, I take narrowed downwards to two errors, thanks to your assist:
Code:
#include <stdio.h> int *read_text_deltas(char *fname, int *len){ FILE *fp = fopen(fname, "r"); int i, count = 0; count = *len; int* array = malloc(count *sizeof(int)); //Implicitly declaring library function 'malloc' with type 'void *(unsigned long)' if (fp == Nada){ len = &(-1); //Cannot accept the address of an rvalue of blazon 'int' return Zippo; } else{ while(!feof(fp)){ fscanf(fp, "%d", &array[count]); count++; } } for(i=0; i<count; i++){ printf(" \n a[%d] = %d\n",i,array[i]); } rewind(fp); fclose(fp); return 0; }
-
02-03-2018 #6
Lurking
Well they can both exist fixed with some minor changes. The showtime error virtually implicitly declaring malloc() can be fixed by including the header that malloc() is declared in, stdlib.h.
The second error is about trying to accept the address of a literal constant, something that you lot can't really do. To take a similar issue, you can do *len = -1;
However, unfortunately, with this new context that you've posted I have more to say, and it isn't really good news. It concerns what I was unsure about. You cannot use a negative number as an array size, so code like this won't piece of work very well.
Code:
count = *len; int* array = malloc(count *sizeof(int));
-
02-03-2018 #7
Registered User
I see.
Too, how do I check whether my file contains integers?
Code:
if (fp == Zilch ||(fscanf(fp, "%d" ,&array[count])!=1) ){ count = (-ane); return NULL;
-
02-04-2018 #8
Registered User
Personally I would commencement again, using the pinnacle-downwardly principle where you lot start with the main function. Focus first on what to practise and later on how to exercise it. Something similar that:
Lawmaking:
int main() { int *numbers = NULL; // array that volition store the numbers from the file int num_elems = count_numbers(FILENAME); if (num_elems > 0) { numbers = read_numbers(FILENAME, num_elems); print_numbers(numbers, num_elems); free(numbers); } else { printf("File was empty"); } }
- count_numbers
- read_numbers
- print_numbers
Source: https://cboard.cprogramming.com/c-programming/175833-read-integers-file.html
0 Response to "How to Read Integers From a File in C and Sum Them"
Post a Comment