Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read a File and Store in a 2d Array

Member Avatar

Yous'd have to resize your 2-dimensional array equally you read the file. Initially you should allocate the array dynamically using malloc(). So read from the file and when you lot run into assortment boundaries expand it using realloc().

Member Avatar

Then read from the file and when you run into assortment boundaries expand information technology using realloc().

An alternative would be a two pass algorthm that counts the number of lines and maximum number of columns for the first laissez passer, so allocates the assortment and populates it in the second pass. That way you avoid expensive calls to realloc(). Whether this is more efficient would need to exist tested though, as reading from a file can be expensive as well. ;)

I recollect the two laissez passer solution is cleaner and would be easier to empathize for a beginner.

Member Avatar

Try this instead:

              #include <fstream> #include <iostream> #include <string>  using namespace std;  int primary() {     ifstream in("output/alignskewresultsgenesnormal.txt");      if (in) {         string line;         int n = 0;          while (getline(in, line)) {             cout << line << '\n';             ++n;         }          cout << n << " lines detected" << endl;     }     else {         cout << "Error opening file" << endl;     } }                          

I want to dominion out issues with the broken use of eof() equally a loop condition and brand certain that errors are properly checked.

p.s. Your code is C++. Should I motion this thread to the C++ forum, or are y'all actually trying to write C?

Member Avatar

no i'm really trying to write in C, but this is my first time i try to do it.

Member Avatar

I recall the two pass solution is cleaner and would be easier to sympathise for a beginner.

Probably. Non sure nigh performance though especially if yous want to consider rows not necessarily accept the same amount of items. (You'd have to allocate every row size to the size of the row containing about elements. Yous'd so have to rails the amount of occupied slots per row or work with sentinal values which might non also exist possible. (although he does but mention positive integers)

To keep it simple, here's example code you lot can use to read in a file with the folowing format:

              1859 1974 726 1684 3048 6243 1853 1896 763 1738 3298 6250 2011 1715 877 1647 3548 6250 2125 1769 648 1685 4213 6227 2047 1858 661 1681 4463 6247 2272 1839 486 1653 4713 6250 2219 1843 497 1616 4963 6175 1679 1420 1234 1901 5648 6234 1522 1851 1060 1817 5898 6250                          

More specifically the code assumes the following for correct functioning:

  • Every row contains an equal corporeality of numbers.
  • Every line ends with a newline. (to be more realistic I immune the last line to not terminate in a newline)
  • Values are seperated by a single whitespace. (infinite or newline)

I did non presume the amount of rows is equal to the corporeality of columns every bit this is non the case in your example either. Many of these points are easy to adjust but they would make the code more circuitous which I didn't want to do for this instance.

Taking these contraints it would look somewhat like the following:

              #include <stdio.h> #include <ctype.h>  int primary(void) {     FILE *file  = NULL;     int symbol  = 0,         columns = 0,         rows    = 0;      // Attempt to open the file "file.txt" with reading persmissions.     file = fopen("file.txt", "r");      // It succeeded!     if (file != NULL)     {         do         {             // Obtain a single character from the file.             symbol = fgetc(file);              // Read character by character to determine the amount of columns on the first row.             // Because every number is followed by a whitespace this equals the corporeality of items on a row.             if (rows == 0 && (isspace(symbol) || feof(file)))             {                 columns++;             }              // Every row is followed by a newline. Only the terminal 1 needn't exist.             if (symbol == '\northward' || feof(file))             {                 rows++;             }         }         while (symbol != EOF);          // Some error occurred during reading.         if (ferror(file))         {             printf("Error on reading from file.\n");         }         // No errors occurred, impress the results.         else         {             printf("The file contains %d row(due south) and %d column(south).\north", rows, columns);         }          // Shut the file.         fclose(file);     }     // Opening the input file failed.     else     {         perror("Error on opening the input file");     }      render 0; }                          

There'south alternatives, for example reading whole lines. The trouble with that is not knowing beforehand how big your buffer should exist. (that's what yous're trying to observe out in the starting time place) This trouble doesn't occur when reading character by graphic symbol.

Member Avatar

so i think i should just alter some if in the code and it volition work correctly

No alter should be needed as I check for whitespaces, non for spaces. If multiple whitespaces may occur in a row y'all will accept to adjust the code although it'south minor. If you need help let me know.

only now my problem is how to include the file inside a 2D array.

You lot're going in the right management. Yous should still watch out with how many times your loops iteratie. They both iterate one time too many now. You either take to replace '<' with '<=' or remove "+1".

As far as fscanf() goes, it requires a format string and memory addresses to place data in. The function clarification I linked contains information about character combinations possible and what they practice. In your case yous'll want:

              fscanf(file, "%d", &(myarr[k][i]));                          

How to Read a File and Store in a 2d Array

Source: https://www.daniweb.com/programming/software-development/threads/437151/read-integers-from-text-file-to-2d-array-in-c