Thread: Copying text to dynamic array and priting it

  1. #1
    Registered User
    Join Date
    Oct 2018
    Posts
    1

    Exclamation Copying text to dynamic array and priting it

    Good day here everybody. I am kind of new in programming. I have to copy stuff(textfile) to array through struct. I already allocated the memory for it. I have no clue how to copy stuff to that dynamic array. After every log (7lines) there is one white line. In this function i have to just alocate it and copy it to array and print it. I will be doing other stuff like, finding item, adding new logs etc. in different functions. Can somebody help me please?

    inf.txt this is my file
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    typedef struct {
        char name[50];
        char gen;
        int  birth;
        char car;
        int  type;
        int  fee;
        long date;
    }log;
    
    int copy() {
        FILE *file;
    char logchar;
    int line=1,numlog=0,i;
    log *p;
     file = fopen("inf.txt", "r");
      while(!feof(file))
        {
            logchar = fgetc(file);
    if(logchar== '\n')
            {
                line++;
            }
        }
        if(line%8==0)
            {
                numlog=(line/8);
             }
            p=(log*)malloc(numlog*sizeof(log));
    
    Last edited by Zenzal; 10-29-2018 at 11:52 AM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Well, currently you're reading the file character-by-character, and then throwing every single character away other than the new-line character, which seems like a bad plan.

    Why not read an entire line from the file using fgets() into a buffer? You don't have to worry about manually searching for new-line, since that's what fgets naturally stops on; and then you can read information from that buffer using whatever tool is appropriate based on how the information is formatted (e.g. sscanf()).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-18-2011, 10:37 AM
  2. Replies: 16
    Last Post: 11-09-2011, 02:56 PM
  3. text file copying incorrectly
    By IsmAvatar2 in forum C Programming
    Replies: 2
    Last Post: 05-13-2007, 11:23 AM
  4. Borland c++ quick reports priting
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 04-30-2002, 07:22 PM
  5. text copying program help
    By rrmusic in forum C++ Programming
    Replies: 2
    Last Post: 04-28-2002, 05:54 PM

Tags for this Thread