Thread: Pick data from file store in array

  1. #1
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005

    Pick data from file store in array

    Hey guys.

    I am wondering say I have a text file like this:

    Name: xxx
    Address: ==
    Tel: 000
    Name: x
    Address: =
    Tel 0
    etc etc
    And in main() I declare an array to store some data:

    char names[ SIZE ][ LENGTH ]
    Is it possible to use either fscanf or fgets to store only the names in
    this array?

    So basically my unsuccessful attempt was:

    #include "telebase.h"
    #include <stdio.h>
    #include <stdlib.h>
    /*function to initilize data members to a default state*/
    void initilizeDataMembers ( struct TeleBase *tb ) {
    	FILE *inFile;
    	inFile = fopen( "telephonelog.txt", "r" );
    	if ( inFile != NULL ) {
    		while ( fgets( tb->name, sizeof( tb->name ), inFile ) != NULL ) {
    			printf("%s\n", tb->name );
    		fclose( inFile );
    	else {
    		printf("Cannot open file!\n");
    Which stores the entire file into the array which I do not want, I just want
    the first line of each one, ( ie the name of each telephone contact ) in
    this one array.

    So far I have only learnt fprintf and fscanf basics when dealing with files, is
    there another C file function that can do this, or am I on the right tracks?

    btw tb is a data struct.

    Any help greatly appriciated
    Double Helix STL

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    You need to read in all the lines, because you can't get from line 1 to line 4 without going through lines 2 and 3. But: the "f" in scanf stands for format. The format you wish to match is the literal "Name: " followed by everything to the new line. So do that:
    if (sscanf(buffer, "Name: %[^\n]", array[i]) == 1) {
        //read in, so move i and do whatever else you need to do

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do you input data from a file into an array?
    By jorgejags in forum C Programming
    Replies: 5
    Last Post: 11-03-2008, 02:48 PM
  2. Replies: 3
    Last Post: 02-26-2008, 02:12 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Replies: 4
    Last Post: 06-14-2005, 05:45 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM