Read Integers From Text File in C

  1. #1

    hughng92 is offline

    Registered User


    Read integers from a file

    Hullo,
    I am trying to read integer from a .txt file and and so shop the integers in the allocated array using malloc(). My thought is as following:

    Code:

                            

    int *read_text(char *fp, int *size); FILE *fp; fp=fopen("/Users/HughNguyen/Google Drive/Notability/CSCI 2021 Lab/Project1/data/brusk.txt", "r"); char* array; int i, count = 0; array = malloc(len*sizeof(char)); if (fp == NULL){ size = -1; return NULL; } else{ while(!feof(fp)){ fscanf(file, "%d", &array[count]); count++; } } for(i=0; i<count; i++){ printf(" \north a[%d] = %d\n",i,assortment[i]); } rewind(fp); fclose(fp); render 0;


    Here is my reason:
    • I open the file using fopen() and I go 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 employ rewind() function to go back to the starting time of the file and then reads integers into my assortment. Close the file when I am done reading all ints. I take to return a arrow to the allocated array.
    • The argument "size" in "int *read_text( char *fp, int *size)" indicates a arrow to an integer which is set to the length of the allocated array. I want to set up a condition that if my file cannot be opened using fopen(), and then volition set my size to -1 and return NULL.
    • This is a role of the whole program. There are three parts: text_main text_main.c read_text.c.

    I have some errors such as:
    • Redefinition of 'fp' with a dissimilar type: 'int' vs 'FILE *'
    • Use of undeclared identifier 'size'
    • A parameter list without types is only allowed in a function definition

    How can I navigate these errors?
    Any tip will be greatly appreciated. Thanks!


  2. #two

    whiteflags is offline

    Lurking whiteflags's Avatar


    As for your errors, tin you 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 haven't you used size?

    Well, anyway, to read a file of integers, I think the simplest code is something like this:

    Lawmaking:

    int *array = malloc( (?) * sizeof(*assortment));  if (array == NULL) {    perror("malloc"); // or any other error handling code    return EXIT_FAILURE; }  for (int i = 0; i < count; i++) {    fscanf(fp, "%d", &array[i]); }
    This is dainty and simple particularly if you're certain that there will be no problems reading the file; in other words, all the text is guaranteed to be representable C integers. Unfortunately, every bit you tin tell from the example, we need to know what to put for the question marker, and that is non every bit straight forward. The problem is that using fscanf to count integers alee of time is difficult. One thing standing in your mode is the format cord itself. At offset glance, a format string that suppresses the assignment to the array appears that it might piece of work, so y'all try something like:

    Code:

    while ( (rv = fscanf(fp, "%*d")) > 0) count++;
    The trouble with this is, fscanf has to succeed at assigning something in order to return successfully (i.e. with a value of at least 1 for 1 match).

    For this reason I think it is much easier to make a guess at the size of the assortment that y'all demand, and if you know how, embiggen the array as you read.

    Lawmaking:

    size_t cap = xv, size = 0; void *temp = NULL; int *array = malloc(cap * sizeof(*assortment));  while (fscanf(fp, "%d", &array[size]) == 1) {    size++;    if (size == cap) {       cap *= 2;       temp = realloc(array, cap * sizeof(*array));       if (temp == Null) {          perror("realloc");          gratuitous(temp);          return EXIT_FAILURE;       }       assortment = temp;    } }
    Of course, y'all could only make a really big assortment and count the size if you don't want to practise all of this piece of work.


  3. #three

    hughng92 is offline

    Registered User


    Hullo WhiteFlags,
    Thank you for your response. I am happy to explicate myself.
    • Commencement, my bad for picking the proper name. I should accept named fp as "fname" as in "file name".
    • I think I did use size as in: char* array = malloc(*size*sizeof(char));
    • How do you put your code in the style in your mail? It looks then cool!
    • There are certain ways to exercise this input style, but I need to stick to the this open source project challenge instructions.

    Code:

    int *read_text_deltas(char *fname, int *len){   FILE *fname = fopen("text.txt", "r"); int i, count = 0; char* assortment = malloc(*len*sizeof(char)); if (fname == Zippo){     len = -ane;     return Nada; } else{     while(!feof(fname)){     fscanf(fname, "%d", &array[count]);     count++;     } } for(i=0; i<count; i++){     printf(" \n a[%d] = %d\north",i,array[i]); } rewind(fname); fclose(fname); return 0;                                              }                                          


  4. #4

    whiteflags is offline

    Lurking whiteflags's Avatar


    • Ah okay, are you sure that you didn't mean something similar this instead?

      Code:

                                FILE *fp = fopen(fname, "r");
      That would make the most sense to me, as fname would be the path and file proper noun string, whereas fp is the name of the variable.

      You lot keep renaming your file variable the aforementioned as your cord!

    • Okay, well, little things matter. In the original code, there was int *size, and you used len (a non-arrow with the wrong name).
    • I postal service code in [code][/code] tags like everyone else. If your source has no other formatting, the syntax would exist highlighted for yous too.

    I'm yet uncertain, but yous might want to practice something similar this.

    Code:

    count = *len; assortment = malloc(count * sizeof(*assortment));
    That is, I want you to save *len to count then that count has a nonzero value. It makes your lawmaking work somewhat ameliorate, only I think that what I showed, with the gradually growing assortment, is really what would work and what should pass for the challenge.

    Also, is there a reason you alleged the array as a char*? Since nosotros're reading integers with "%d", it's appropriate to use int, not char.


  5. #five

    hughng92 is offline

    Registered User


    So actually, fname volition represent for any the name of the file I am going to laissez passer in the function fopen() right?
    In my text_main.c, I take:

    Code:

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include "deltas.h"   int main(int argc, char *argv[]){   if(argc < 3){     printf("usage: %s <format> <filename>\north",argv[0]);     printf(" <format> is one of\n");     printf(" text : text ints are in the given filename\n");     printf(" int  : binary ints are in the given filename\n");     printf(" 4bit : 4bit binary ints are in the given filename\north");     return 1;   }   char *format = argv[1];   char *fname = argv[2];     int data_len = -1;   int *data_vals = NULL;   if( strcmp("text", format)==0 ){     printf("Reading text format\due north");     data_vals = read_text_deltas(fname, &data_len);   }   else if( strcmp("int", format)==0 ){     printf("Reading binary int format\n");     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'\n",format);     return 1;   }     printf("data_len: %d\n",data_len);   printf("%4s %4s\due north","#","read");   for(int i=0; i<data_len; i++){     printf("%4d %4d\due north",i,data_vals[i]);   }     free(data_vals);      return 0; }
    I am thinking "fname" may be divers in this file text_main.c. I take never used fopen() before and I am pretty new to C. I saw some posts online showing how to use fopen such as fopen("file.text","r").
    Y'all are right about my array proclamation. I must use int.
    Now, I have narrowed down to ii errors, cheers 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* assortment = malloc(count *sizeof(int)); //Implicitly declaring library function 'malloc' with type 'void *(unsigned long)' if (fp == Zip){     len = &(-ane); //Cannot take the address of an rvalue of type 'int'     return NULL; } else{     while(!feof(fp)){     fscanf(fp, "%d", &array[count]);     count++;     } } for(i=0; i<count; i++){     printf(" \n a[%d] = %d\north",i,array[i]); } rewind(fp); fclose(fp); return 0; }
    What do these two errors mean to my logics of the program?


  6. #6

    whiteflags is offline

    Lurking whiteflags's Avatar


    Well they can both be fixed with some pocket-sized changes. The get-go error almost implicitly declaring malloc() can be fixed by including the header that malloc() is declared in, stdlib.h.

    The second mistake is about trying to take the address of a literal constant, something that you lot can't really do. To have a similar event, you can do *len = -ane;

    Nevertheless, unfortunately, with this new context that yous've posted I accept more than to say, and it isn't actually good news. It concerns what I was unsure most. You cannot use a negative number as an array size, so lawmaking like this won't work very well.

    Code:

    count = *len; int* array = malloc(count *sizeof(int));
    Yous're all-time bet is to become back to my first post in this thread and endeavour to implement one of the ideas.


  7. #7

    hughng92 is offline

    Registered User


    I run into.
    Also, how practice I check whether my file contains integers?

    Code:

                                                  if                                              (fp == Zero ||(fscanf(fp,                                              "%d"                      ,&array[count])!=i) ){     count = (-1);                                              return                                              Aught;


  8. #eight

    OldGuy2 is offline

    Registered User


    Personally I would start once more, using the top-downward principle where you commencement with the main function. Focus kickoff on what to do and later on on how to do information technology. Something like that:

    Code:

    int main() {   int *numbers = NULL; // array that will shop 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);     gratuitous(numbers);   }   else   {     printf("File was empty");   } }
    Next step would be to implement the functions
    1. count_numbers
    2. read_numbers
    3. print_numbers


stewardnathe1994.blogspot.com

Source: https://cboard.cprogramming.com/c-programming/175833-read-integers-file.html

0 Response to "Read Integers From Text File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel