C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 07-10-2009, 09:29 AM   #1
Its hard... But im here
 
swgh's Avatar
 
Join Date: Apr 2005
Location: England
Posts: 1,466
Pick data from file store in array

Hey guys.

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

Code:
Name: xxx
Address: ==
Tel: 000

Name: x
Address: =
Tel 0

etc etc
And in main() I declare an array to store some data:

Code:
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:

Code:
#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
__________________
I'm just trying to be a better person - My Name Is Earl
swgh is offline   Reply With Quote
Old 07-10-2009, 09:57 AM   #2
and the Hat of Guessing
 
tabstop's Avatar
 
Join Date: Nov 2007
Posts: 8,740
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:
Code:
if (sscanf(buffer, "Name: %[^\n]", array[i]) == 1) {
    //read in, so move i and do whatever else you need to do
}
tabstop is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
how do you input data from a file into an array? jorgejags C Programming 5 11-03-2008 02:48 PM
Need Help: Storing numeric data into matrix from a data file spiit231 C Programming 3 02-26-2008 02:12 PM
Can we have vector of vector? ketu1 C++ Programming 24 01-03-2008 05:02 AM
[question]Analyzing data in a two-dimensional array[with code] burbose C Programming 4 06-14-2005 05:45 AM
Binary Search Trees Part III Prelude A Brief History of Cprogramming.com 16 10-02-2004 03:00 PM


All times are GMT -6. The time now is 05:47 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22