473,564 Members | 2,798 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Learning pointers and arrays of pointers With Files

Hello, I was wondering if someone could help me with a function I am
trying to write. The purpose of the function is to read in text from a
file in the following format:

FIRSTNAME LASTNAME SCORE SCORE SCORE SCORE

example:

Karen Smith 100 100 100 100
John Oliver 78 90 65 51
Henry Green 44 55 44 44

I basically want to pass the number of lines or records, a file
pointer, a pointer to a char array, a pointer to another char array,
and a pointer to an int array to a function that will read all the file
input up to the first space into the first element of the first char
array, then all the next characters up to the second space into the
first element of the second char array, then all the integers into the
first element of the int array. This is what I have so far:

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

void readLines(int numLines, FILE *, char *firstNames[], char
*lastNames[], int *scores[]);

//variables
FILE *inputFile;
int numRecords = 0;

...get number of records from user...

char *firstNames[numRecords]; //array of pointers
char *lastNames[numRecords];
int *scores[4]; //We know there are always 4 for each line
scores
inputFile = fopen("input.tx t", "r"); //open the input file

readLines(numRe cords, inputFile, firstNames, lastNames,
scores);

void readLines(int numLines, FILE *file, char *firstNames[], char
*lastNames[], int *scores[]){
int i = 0;

for(i = 0; i < numLines; i++){
while(firstName s[i] = (getc(FILE *file)) ){//this is
where i need
help...
want to read placing each char into firstNames[i]
until i hit a space,then
start putting chars into lastNames[i] until i hit
the next space then read each int placing
each one into a spot in scores[0]

}
}

}

Thanks for the feedback
Ketema

Nov 14 '05 #1
1 1603
ke****@gmail.co m wrote:
Hello, I was wondering if someone could help me with a function I am
trying to write. The purpose of the function is to read in text from a
file in the following format: FIRSTNAME LASTNAME SCORE SCORE SCORE SCORE example: Karen Smith 100 100 100 100
John Oliver 78 90 65 51
Henry Green 44 55 44 44 I basically want to pass the number of lines or records, a file
pointer, a pointer to a char array, a pointer to another char array,
and a pointer to an int array to a function that will read all the file
input up to the first space into the first element of the first char
array, then all the next characters up to the second space into the
first element of the second char array,
What about people with names like "George W. Bush"?;-)
then all the integers into the
first element of the int array. This is what I have so far: #include <stdio.h>
#include <ctype.h>
#include <string.h> void readLines(int numLines, FILE *, char *firstNames[], char
*lastNames[], int *scores[]);
I guess this was meant to be

int main( void )

or maybe

int main( int argc, char *argv[ ] )
//variables
FILE *inputFile;
int numRecords = 0; ...get number of records from user...
It might be a better idea to iterate over the file to find out how
many lines are there instead of believing the user...
char *firstNames[numRecords]; //array of pointers
This won't work unless you have a C99 compliant compiler - with
C89 there where no variables sized arrays, the size has to be a
compile time constant.

And just creating an array of pointers won't work. All these pointers
are uninitialized, i.e. they point to some random memory locations,
not to memory you can use. Before you can write strings to where
the pointers point to you have to obtain memory from the system
using e.g. malloc().
char *lastNames[numRecords];
int *scores[4]; //We know there are always 4 for each line
scores
But than you would need numRecords times 4 integers, not 4 pointers.
inputFile = fopen("input.tx t", "r"); //open the input file
You forget to check if fopen() failed.
readLines(numRe cords, inputFile, firstNames, lastNames,
scores); void readLines(int numLines, FILE *file, char *firstNames[], char
*lastNames[], int *scores[]){
int i = 0; for(i = 0; i < numLines; i++){
while(firstName s[i] = (getc(FILE *file)) ){//this is
I guess you mean "getc(file) " here. But anyway, firstNames is an
array of pointers, so "firstNames[i]" is the i-th pointer, not some-
thing were you could store a character. And getc() returns an int,
not a char, since EOF can't be represented as a char (and 0 is not
a return value that tells you that EOF has been reached as you seem
to assume, (char) '\0' is a valid charcter, but which you won't find
in a text file).
where i need
help...
want to read placing each char into firstNames[i]
until i hit a space,then
start putting chars into lastNames[i] until i hit
the next space then read each int placing
each one into a spot in scores[0]


Sorry, but all of this is that wrong that I would really recommend
that you start with some simpler things for learning about pointers.
As the next step find out how the functions malloc(), realloc() and
free() are used. When you have mastered that you may be ready for
trying something like this here. I can tell you it's quite tricky
to get it right for all cases, and without a clearer understanding
of pointers and memory allocation I fear you won't be able to do
that.

A task which might help you understand quite a bit would be writing
a function that reads in an arbitraty long line from a file passed
to the function, returning a pointer to the string. Such a function
could be a building block for your program and would get you fami-
liar with the functions for memory allocation. Here's a way it it
might be done:

1) Define a char pointer
2) Allocate a certain amount of memory, e.g. 128 characters (some-
thing long enough for typical lines), using malloc() and assign
the result to the char pointer. Don't forget to check the return
value of malloc().
3) Read characters from the file, putting them into the memory poin-
ted to by the char pointer. Keep track of how many you read and
how long the buffer is the char pointer is pointing to.
4) If there are no more characters go to 6
5) If the memory you got is filled up use realloc() to double the
amount of memory the char pointer is pointing to and continue
with 3. Don't forget to check the return value of realloc()
and make sure you have a backup of the original value of the
pointer in case realloc() fails.
6) Put a '\0' after the last character in the buffer pointed to by
the char pointer. Make sure there's still enough place in the
buffer for the '\0' character.
7) Use realloc() to cut back on the size of the buffer so that only
that much space is used as is absolutely necessary.
8) Return the char pointer.

Of course, the calling function must later free() the pointer.
Put that prominently into the documentation of the function.
Test the function carefully to check that all corner cases are
treated correctly and you never write past the end of the memory
you allocated - if you get it wrong it might seem to work at first
but then fail mysteriously sometime later or even lead to errors
in seemingly unrelated places!

Once you mastered this I guess you will have a pretty good idea
how to deal with several input lines, each having several entries
(consider using double pointers for the first and last names if
you forego using variable sized arrays). And you could use that
function (perhaps after a few minor modifications) for that.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
1612
by: Javier | last post by:
Hi I'm trying to learn how to use pointers with a little example. I did: void main(int argc, char* argv) { char algo = "Algo mas"; char * p = algo;
9
3869
by: the_philospher | last post by:
I am a beginner programmer learning c++. i have read some useful information about programming games (which is my goal) on gamedev.net, particularly "how do i program games" http://www.gamedev.net/reference/design/features/makegames/. the article suggests first programming a tetris clone, then moving on to "breakout", "pacman", and a super...
36
2810
by: raphfrk | last post by:
I have the following code: char buf; printf("%lp\n", buf); printf("%lp\n", &buf); printf("%lp\n", buf); printf("%lp\n", buf); printf("%d\n", buf-buf);
8
1527
by: macawm | last post by:
Hi all, What is the difference between these two statements? int* a = new int and int a The reason I ask is because this int len = sizeof(a) / sizeof(*a) works for the second construct, but not the first.
36
2500
by: utab | last post by:
Dear, I have experince in C( numerical projects, like engineering problems, scientific applications) I have the basic notion of C++ also, I have read Accelerated C++ until Chapter 7, however it seems that it discusses the std and the other part of the language with your own abstractions. Is that better to read a book first on the basic...
21
1809
by: jonathanmcdougall | last post by:
I just got a new job yesterday where most of the programming is done in C. Although I have several years of experience in C++ and other object-oriented languages, I have next to none in C. What I am looking for is a book (or some other resource) on "how to learn C if you already know C++" or, more exactly, "how to program in a procedural...
23
7371
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion....
6
1482
by: JoeC | last post by:
I understand the basics of pointers, they point to memory locations. I would like to know resources for learning all about poters. I am having some problems erasing elements of pointers from a vector. I wold like to know where I can get some in depth information on how to use pointers in various situations. It seems that all most books...
8
2901
by: Piotrek | last post by:
Hi, Like almost all of beginners I have problem understanding pointers. Please, look at this piece of code, and please explain me why myswap function doesn't work as it's supposed to do, whereas myswap2 is doing exactly what I want it to do - swaping pointers. Where I made a mistake? Thanks void myswap(char *pa, char *pb){ char *tmp;...
0
7665
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
3643
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.