473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to read string out of file with pointer?

Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
....
(the string sould not contain ' ' anyway)
the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first read the string to get the length, then read again and save it to the array. Is there any better way?
I would not like to use array with certain length since I don't know how long could a string be.

Thanks in advance!

Xinyi
Nov 13 '05 #1
10 10220
Xinyi Yang <ic***@slds1.de.lucent.com> wrote:
Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
...
(the string sould not contain ' ' anyway) [ Please cut down your line length, text reformatted:]the size of each string is uncertain. I plan to create an array
to contain the pointers to the strings. Yet I don't know how to
read a string out from the file any let a pointer point to it.
I thought about using char *p=(int *) (malloc(n*(sizeof(char)))),
but it means I have to first read the string to get the length,
then read again and save it to the array. Is there any better way?
I would not like to use array with certain length since I don't
know how long could a string be.

1. use a dynamically reallocated array of pointers-to-char

2. write a function, which
- reads one character at a time from the file
- store it in a dynamically reallocated character buffer
- terminates the buffer with '\0'
- assigns the pointer to the first character in the resulting
string to the next free place in the first array.

If you get stuck on the way, feel free to post your code (reduced to
the smallest posssible compilable version) here to exhibit your
particular problem.

Regards

Irrwahn
--
The generation of random numbers is too important to be left to chance.
Nov 13 '05 #2

why don't you try sscanf() ?
--
Posted via http://dbforums.com
Nov 13 '05 #3
Xinyi Yang wrote:
Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
....
(the string sould not contain ' ' anyway)
the size of each string is uncertain. I plan to create an
array to contain the pointers to the strings. Yet I don't know
how to read a string out from the file any let a pointer
point to it. I thought about using char *p=(int *)
(malloc(n*(sizeof(char)))), but it means I have to first read
the string to get the length, then read again and save it to
the array. Is there any better way? I would not like to use
array with certain length since I don't know how long could a
string be.


Xinyi...

You might get some ideas from the code at:

http://www.iedu.com/mrd/c/tokenize.c and
http://www.iedu.com/mrd/c/tokfile.c

"Better way" depends much on your input data and program
objectives. The example code assumes that there is sufficient
memory available.
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c

Nov 13 '05 #4
Xinyi Yang wrote:

Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
...
(the string sould not contain ' ' anyway)


[snip]

Hi Xinyi,

Your short description of the file format looks to me like a text file
consisting of lines of fields of characters, separated by commas. That
might describe a database table file. Does it?

Text files don't generally contain strings. A string is a memory thing,
an array of char terminated by and including the '\0' (NUL) character.

It is crucial to understand everything about the input file in order to
read anything useful from it. Maybe you can give us more information?
--
Joe Wright mailto:jo********@earthlink.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #5
On Fri, 19 Sep 2003 08:26:35 -0400, dreamcatcher
<me*********@dbforums.com> wrote in comp.lang.c:

why don't you try sscanf() ?


....because it sucks?

For some definitions of "suck", such as poor error recovery, potential
for undefined behavior, complexity of use, and extreme difficulty in
using correctly.

Yes, sucks.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #6
Joe Wright wrote:

Hi Xinyi,

Your short description of the file format looks to me like a text file
consisting of lines of fields of characters, separated by commas. That
might describe a database table file. Does it?
Yes, sth like that.
Text files don't generally contain strings. A string is a memory thing,
an array of char terminated by and including the '\0' (NUL) character.
I just want to read the section of characters out as a string and later
store them in a structure.
It is crucial to understand everything about the input file in order to
read anything useful from it. Maybe you can give us more information?


Well, this text file contains sections of characters from 0-9, a-z, A-Z.
Each section is seperated by commas. The length of the section is unknown.
And now I would like to get the section as a string and later store a pointer
of the string in an array. That's it.

Thanks!

--
Xinyi Yang
Nov 13 '05 #7
dreamcatcher wrote:

why don't you try sscanf() ?


Because the section is seperated with ',' , but not space. So if you use sscanf(), it will get the whole text for you.

--
Xinyi Yang
Nov 13 '05 #8
Xinyi Yang <ic***@slds1.de.lucent.com> wrote in message news:<3F***************@slds1.de.lucent.com>...
Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
...
(the string sould not contain ' ' anyway)
the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first read the string to get the length, then read again and save it to the array. Is there any better way?
I would not like to use array with certain length since I don't know how long could a string be.

Thanks in advance!

Xinyi


The way I'd attack this is to create a dynamic buffer of size X using
malloc(), then reading a single character at a time into the dynamic
buffer, extending it as necessary using realloc(), until you see
either a ',' or EOF.

Quick, dirty, untested example:

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

#define START_SIZE 20 /* Initial buffer size */
#define EXTENT 5 /* Size to extend buffer by */

char *nextToken (FILE *in)
{
char *tmp, *p;
int phys_size = START_SIZE, cur_size = 0;
int nextchar;

/*
** Note: Do not cast the return value of malloc() unless
** you are using a pre-C89 compiler.
*/
p = malloc (START_SIZE);

if (p)
{
/*
** consume any leading whitespace
*/
while (isspace(nextchar = fgetc (in))
/* empty loop */;

while (nextchar != ',' && nextchar != EOF)
{
if (cur_size == phys_size - 1)
{
/*
** We've hit the end of the buffer.
** Use realloc() to extend it by
** EXTENT characters. For this example,
** a realloc() failure is a fatal error
** and we exit the program immediately.
** With a little effort you could make
** this handle such an error more gracefully.
*/
tmp = realloc (p, phys_size + EXTENT);
if (!tmp)
{
fprintf (stderr, "Buffer extend failed! Fatal
error!\n");
fflush (stderr);
exit (0);
}
phys_size += EXTENT;
p = tmp;
}
p[cur_size++] = c;
}
p[cur_size] = 0; /* terminate the string */
}

return p;
}
Nov 13 '05 #9
jo*******@my-deja.com (John Bode) wrote in message news:<43**************************@posting.google. com>...
Xinyi Yang <ic***@slds1.de.lucent.com> wrote in message news:<3F***************@slds1.de.lucent.com>...
Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
...
(the string sould not contain ' ' anyway)
the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first read the string to get the length, then read again and save it to the array. Is there any better way?
I would not like to use array with certain length since I don't know how long could a string be.

Thanks in advance!

Xinyi
The way I'd attack this is to create a dynamic buffer of size X using
malloc(), then reading a single character at a time into the dynamic
buffer, extending it as necessary using realloc(), until you see
either a ',' or EOF.

Quick, dirty, untested example:

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

#define START_SIZE 20 /* Initial buffer size */
#define EXTENT 5 /* Size to extend buffer by */

char *nextToken (FILE *in)
{
char *tmp, *p;
int phys_size = START_SIZE, cur_size = 0;
int nextchar;

/*
** Note: Do not cast the return value of malloc() unless
** you are using a pre-C89 compiler.
*/
p = malloc (START_SIZE);

if (p)
{
/*
** consume any leading whitespace
*/
while (isspace(nextchar = fgetc (in))

) /* oops */ /* empty loop */;

while (nextchar != ',' && nextchar != EOF)
{
if (cur_size == phys_size - 1)
{
/*
** We've hit the end of the buffer.
** Use realloc() to extend it by
** EXTENT characters. For this example,
** a realloc() failure is a fatal error
** and we exit the program immediately.
** With a little effort you could make
** this handle such an error more gracefully.
*/
tmp = realloc (p, phys_size + EXTENT);
if (!tmp)
{
fprintf (stderr, "Buffer extend failed! Fatal
error!\n");
fflush (stderr);
exit (0);
}
phys_size += EXTENT;
p = tmp;
}
p[cur_size++] = c; p[cur_size++] = nextchar; /* oops^2 */

nextchar = fgetc (in); /* oops^3 */ }
p[cur_size] = 0; /* terminate the string */
}

return p;
}

Nov 13 '05 #10
jo*******@my-deja.com (John Bode) wrote in message news:<43**************************@posting.google. com>...
Xinyi Yang <ic***@slds1.de.lucent.com> wrote in message news:<3F***************@slds1.de.lucent.com>...
Hi,

I have to read information out of a file. The format will be
string1,string2,...,
string3,string4,...,
...
(the string sould not contain ' ' anyway)
the size of each string is uncertain. I plan to create an array to contain the pointers to the strings. Yet I don't know how to read a string out from the file any let a pointer point to it. I thought about using char *p=(int *) (malloc(n*(sizeof(char)))), but it means I have to first read the string to get the length, then read again and save it to the array. Is there any better way?
I would not like to use array with certain length since I don't know how long could a string be.

Thanks in advance!

Xinyi
The way I'd attack this is to create a dynamic buffer of size X using
malloc(), then reading a single character at a time into the dynamic
buffer, extending it as necessary using realloc(), until you see
either a ',' or EOF.

Quick, dirty, untested example:

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

#define START_SIZE 20 /* Initial buffer size */
#define EXTENT 5 /* Size to extend buffer by */

char *nextToken (FILE *in)
{
char *tmp, *p;
int phys_size = START_SIZE, cur_size = 0;
int nextchar;

/*
** Note: Do not cast the return value of malloc() unless
** you are using a pre-C89 compiler.
*/
p = malloc (START_SIZE);

if (p)
{
/*
** consume any leading whitespace
*/
while (isspace(nextchar = fgetc (in))

) /* oops */ /* empty loop */;

while (nextchar != ',' && nextchar != EOF)
{
if (cur_size == phys_size - 1)
{
/*
** We've hit the end of the buffer.
** Use realloc() to extend it by
** EXTENT characters. For this example,
** a realloc() failure is a fatal error
** and we exit the program immediately.
** With a little effort you could make
** this handle such an error more gracefully.
*/
tmp = realloc (p, phys_size + EXTENT);
if (!tmp)
{
fprintf (stderr, "Buffer extend failed! Fatal
error!\n");
fflush (stderr);
exit (0);
}
phys_size += EXTENT;
p = tmp;
}
p[cur_size++] = c; p[cur_size++] = nextchar; /* oops^2 */

nextchar = fgetc (in); /* oops^3 */ }
p[cur_size] = 0; /* terminate the string */
}

return p;
}

Nov 13 '05 #11

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

Similar topics

4
by: yo_mismo | last post by:
Hi everyone, I'm trying to read the first line of a file this way: .... .... .... .... new_line=0; while((read=read(fd, &info, sizeof(info))) > 0 && !new_line){ if (strcmp(&info, "\n") !=...
19
by: Mark Richards | last post by:
I've been programming for many years, but have only recently taken a deep "C" dive (bad pun, i know) and need a lot of explanation from an expert. My questions center around those mysterious...
1
by: Magix | last post by:
Hi, I have these string data: str_data1, str_data2, str_data3, which capture some value after a routine process A. Then I would like to write (append) these 3 string values into a text file each...
5
by: Pete | last post by:
I having a problem reading all characters from a file. What I'm trying to do is open a file with "for now" a 32bit hex value 0x8FB4902F which I want to && with a mask 0xFF000000 then >> right...
3
by: Dave Coate | last post by:
Hello again, I am going to re-post a question. I got some excellent suggestions from Rob and Mattias on this but their ideas did not solve the problem. Here is the original post: ...
9
by: Adi | last post by:
Hello eveyone, I wanna ask a very simple question here (as it was quite disturbing me for a long time.) My problem is to read a file line by line. I've tried following implementations but still...
1
by: Matrixinline | last post by:
Hi All, File Text.txt Contains following text as : "C:\program file\application data\details\app" "D:\Program File" I tried to read that data as fscanf(oFp, "%s %s", sCopyDirectory,...
3
by: sam | last post by:
same as subject?
6
by: ma740988 | last post by:
I'm perusing a question and curiosity got the best of me in part because I cant solve the problem Consider: typedef unsigned int word_type ; class foo { public: void set_mx_digits_1 (...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...

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.