NewCoder
NewCoder

Reputation: 85

How to create 2D array from text file and print to new file in c

Wondering if I could get some advice. Firstly, I am very new to programming, so I apologise for any silly mistakes. Please feel free to point them out and I will try to go research to improve.

I feel I am doing something fundamentally wrong with my array.

I am trying to read in from a file whose filename is specified by user input, store the information from the file in a 2D array, which I then plan to print into another file, again defined by user input.

I am currently printing out the array, to check that it has been stored, but I believe I am using the 2D array incorrectly, as when I try to fprintf into my file, it just does not work.

Any advice would be greatly appreciated.

Thank you. Code as follows:

#include <stdio.h>
#include <string.h>

int main()
{
   char finame[100];
   printf("Enter file you would like to open: ");
   scanf("%s", finame);
   FILE *in = fopen(finame, "r"); 

   char foname[100];
   printf("Enter the filename you would like the output included in: ");
   scanf("%s", foname);
   FILE *out = fopen(foname, "w");


    /*Char array to store string */
    char str[50][20];

    int i =0;

    /*Loop for reading the file till end*/
    while((fgets(str[i],sizeof(str[i]), in)) != NULL) {
      fputs(str[i++],stdout);
      //getchar();
   }

    return 0;
}

Upvotes: 0

Views: 320

Answers (1)

alex01011
alex01011

Reputation: 1702

  1. Avoid mixing fgets(), scanf() calls. scanf() leaves a newline character in the input buffer which is later consumed by fgets() (doesn't matter in this case since input comes from a file not from stdin but a good practice overall).

There is also no protection for overflow, if you want to stick to scanf() add a width specifier and check the result to see if it succeeded.

   if (scanf("%99s", finame) != 1) /* save one byte for \0 */
   {
       /* handle error case */
   }
  1. Check that you don't exceed the size of your array while writing to it.

Added 2 define directives that could clean your code up.

#define MAX_LINES 50
#define MAX_CHAR 20

char str[MAX_LINES][MAX_CHAR];

    int i = 0;

    while (i < MAX_LINES && (fgets(str[i], MAX_CHAR, in)) != NULL) /* always check if running out bounds */
    {
        fputs(str[i++], stdout);
    }

The problem with the above code is that, if the file gets too big, you will end up missing data, what you could do is have a dynamic array and use a malloc / realloc approach to expand the array or a linked list.

Upvotes: 1

Related Questions