Read Only Integers From Txt File C++

  1. #1

    hughng92 is offline

    Registered User


    Read integers from a file

    How-do-you-do,
    I am trying to read integer from a .txt file and then store the integers in the allocated assortment using malloc(). My thought is equally post-obit:

    Code:

                            

    int *read_text(char *fp, int *size); FILE *fp; fp=fopen("/Users/HughNguyen/Google Bulldoze/Notability/CSCI 2021 Lab/Project1/data/short.txt", "r"); char* array; int i, count = 0; array = malloc(len*sizeof(char)); if (fp == Nada){ size = -1; render Null; } else{ while(!feof(fp)){ fscanf(file, "%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;


    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 classify an array of proper size.
    • I want to apply rewind() function to go back to the start of the file then reads integers into my array. Shut the file when I am done reading all ints. I have to return a pointer to the allocated assortment.
    • 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 assortment. I want to set up a condition that if my file cannot be opened using fopen(), and so will set my size to -1 and return NULL.
    • This is a part of the whole program. In that location are three parts: text_main text_main.c read_text.c.

    I have some errors such as:
    • Redefinition of 'fp' with a different blazon: 'int' vs 'FILE *'
    • Use of undeclared identifier 'size'
    • A parameter list without types is only immune in a role definition

    How can I navigate these errors?
    Whatever tip will be greatly appreciated. Thank you!


  2. #2

    whiteflags is offline

    Lurking whiteflags's Avatar


    As for your errors, can you explain what these parameters are for?

    > int *read_text(char *fp, int *size);
    Why is the first named fp? That seems to be one trouble.
    And why haven't you used size?

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

    Code:

    int *array = malloc( (?) * sizeof(*array));  if (array == Null) {    perror("malloc"); // or any other error treatment code    return EXIT_FAILURE; }  for (int i = 0; i < count; i++) {    fscanf(fp, "%d", &array[i]); }
    This is nice and uncomplicated especially if y'all're sure that there will be no issues reading the file; in other words, all the text is guaranteed to be representable C integers. Unfortunately, as you can tell from the example, nosotros demand to know what to put for the question marker, and that is non equally straight forward. The trouble is that using fscanf to count integers alee of time is difficult. 1 thing standing in your manner is the format cord itself. At showtime glance, a format string that suppresses the assignment to the array appears that it might work, so you 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.eastward. 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 array that you need, and if you lot know how, embiggen the assortment as you read.

    Code:

    size_t cap = 15, size = 0; void *temp = NULL; int *array = malloc(cap * sizeof(*array));  while (fscanf(fp, "%d", &array[size]) == 1) {    size++;    if (size == cap) {       cap *= 2;       temp = realloc(array, cap * sizeof(*array));       if (temp == Goose egg) {          perror("realloc");          free(temp);          render EXIT_FAILURE;       }       array = temp;    } }
    Of course, you lot could just make a really big array and count the size if yous don't want to do all of this work.


  3. #3

    hughng92 is offline

    Registered User


    Howdy WhiteFlags,
    Give thanks you for your response. I am happy to explain myself.
    • Beginning, my bad for picking the name. I should have named fp as "fname" as in "file name".
    • I think I did utilize size as in: char* assortment = malloc(*size*sizeof(char));
    • How do y'all put your code in the mode in your mail service? It looks so absurd!
    • At that place are certain ways to practise this input manner, but I need to stick to the this open up source project challenge 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 NULL; } else{     while(!feof(fname)){     fscanf(fname, "%d", &array[count]);     count++;     } } for(i=0; i<count; i++){     printf(" \n a[%d] = %d\n",i,assortment[i]); } rewind(fname); fclose(fname); return 0;                                              }                                          


  4. #4

    whiteflags is offline

    Lurking whiteflags's Avatar


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

      Lawmaking:

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

      You lot go along renaming your file variable the same equally your cord!

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

    I'm yet uncertain, just you might want to do something like this.

    Lawmaking:

    count = *len; array = malloc(count * sizeof(*array));
    That is, I desire y'all to save *len to count then that count has a nonzero value. It makes your code work somewhat ameliorate, but I call up that what I showed, with the gradually growing assortment, is really what would piece of work and what should pass for the challenge.

    Also, is in that location a reason you declared the array as a char*? Since we're reading integers with "%d", it'south appropriate to use int, not char.


  5. #five

    hughng92 is offline

    Registered User


    And so actually, fname will represent for whatever the proper noun of the file I am going to laissez passer in the function fopen() right?
    In my text_main.c, I have:

    Code:

    #include <stdio.h> #include <stdlib.h> #include <cord.h> #include "deltas.h"   int main(int argc, char *argv[]){   if(argc < 3){     printf("usage: %s <format> <filename>\due north",argv[0]);     printf(" <format> is one of\northward");     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\northward");     return i;   }   char *format = argv[i];   char *fname = argv[2];     int data_len = -1;   int *data_vals = NULL;   if( strcmp("text", format)==0 ){     printf("Reading text format\n");     data_vals = read_text_deltas(fname, &data_len);   }   else if( strcmp("int", format)==0 ){     printf("Reading binary int format\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 1;   }     printf("data_len: %d\due north",data_len);   printf("%4s %4s\n","#","read");   for(int i=0; i<data_len; i++){     printf("%4d %4d\northward",i,data_vals[i]);   }     free(data_vals);      return 0; }
    I am thinking "fname" may be divers in this file text_main.c. I have never used fopen() earlier and I am pretty new to C. I saw some posts online showing how to utilize fopen such as fopen("file.text","r").
    You are correct about my array announcement. I must utilise int.
    Now, I have narrowed downward to 2 errors, thank you to your help:

    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 == Goose egg){     len = &(-1); //Cannot have the address of an rvalue of blazon 'int'     render NULL; } else{     while(!feof(fp)){     fscanf(fp, "%d", &array[count]);     count++;     } } for(i=0; i<count; i++){     printf(" \due north a[%d] = %d\n",i,assortment[i]); } rewind(fp); fclose(fp); render 0; }
    What practice these two errors hateful to my logics of the plan?


  6. #6

    whiteflags is offline

    Lurking whiteflags's Avatar


    Well they tin both be fixed with some minor changes. The first error nigh implicitly declaring malloc() tin can be stock-still 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 can't really do. To have a similar effect, you can exercise *len = -i;

    However, unfortunately, with this new context that y'all've posted I have more to say, and it isn't really good news. Information technology concerns what I was unsure about. You lot cannot use a negative number as an array size, so lawmaking similar this won't work very well.

    Code:

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


  7. #vii

    hughng92 is offline

    Registered User


    I see.
    As well, how do I check whether my file contains integers?

    Code:

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


  8. #eight

    OldGuy2 is offline

    Registered User


    Personally I would starting time again, using the top-downwardly principle where you start with the main role. Focus first on what to do and later on how to exercise it. Something like that:

    Code:

    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");   } }
    Next step would exist to implement the functions
    1. count_numbers
    2. read_numbers
    3. print_numbers


Read Only Integers From Txt File C++

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

0 Response to "Read Only Integers From Txt File C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel