473,686 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C: extract string from file

hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

Nov 14 '05 #1
9 16968
Hello,

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

If your read string was: "1 This is the string 2 3 4" you
can parse it using strncpy() as:

char str[100];
strncpy(str, line+10, 35);
str[35] = 0;
Nov 14 '05 #2

"lallous" <la*****@lgwm.o rg> ¦b¶l¥ó
news:bs******** ****@ID-161723.news.uni-berlin.de ¤¤¼¶¼g...
Hello,

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T") and extract 35 characters (including "T") from a file and then go to next line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

If your read string was: "1 This is the string 2 3 4" you
can parse it using strncpy() as:

char str[100];
strncpy(str, line+10, 35);
str[35] = 0;

sorry, I don't understand
how to get the value of "line" ?
e.g. using functions like "fgetc( file)" ??

Nov 14 '05 #3
On Mon, 22 Dec 2003 17:52:04 +0800, "Sharon"
<sh************ @hotmail.com> wrote:
I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?


I would use fgets to read a line into a character array. Then I would
string copy the section that I wanted into a second character array.
Something like this might work for you:

char* source="1 This is the string 2 3 4";
char destination[26]={0};
strncpy(destina tion, source+10, 25);
printf("\"%s\"\ n", destination);

The output on my system is:

"This is the string "

Note that you need to make sure that the destination array is null
terminated. I did that in the initialization step.
--

Best wishes,

Bob
Nov 14 '05 #4
U¿ytkownik "Sharon" <sh************ @hotmail.com> napisa³ w wiadomo¶ci
news:bs******** ***@news.hgc.co m.hk...

"lallous" <la*****@lgwm.o rg> ¦b¶l¥ó
news:bs******** ****@ID-161723.news.uni-berlin.de ¤¤¼¶¼g...
Hello,

"Sharon" <sh************ @hotmail.com> wrote in message
news:bs******** ***@news.hgc.co m.hk...
hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T") and extract 35 characters (including "T") from a file and then go to next line?

I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

If your read string was: "1 This is the string 2 3 4" you can parse it using strncpy() as:

char str[100];
strncpy(str, line+10, 35);
str[35] = 0;

sorry, I don't understand
how to get the value of "line" ?
e.g. using functions like "fgetc( file)" ??


I think so you didn't keep characters which you read. Your function reading
line of text from file should look like this:

#define MAX_LEN_OF_LINE 256
char line[MAX_LEN_OF_LINE];
int i=0;
memset(line , '\0', sizeof(line));
while (((c=fgetc( file ))!=EOF) && (i<MAX_LEN_OF_L INE-1))
{
if ( c == '\n' ) break;
line[i++]=c;
}

Now you can use strncpy function to extract substring from "line" variable.

Mirek T.
Nov 14 '05 #5

"Sharon" <sh************ @hotmail.com> wrote in message

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?
This is rather an awkward line format. If the string can't contain
whitespace you can use the scanf() family of fuctions. Does the string
always start at position 10? Is it always 35 characters long?
I know how to go to next line but have no idea how to extract string
thank you for answering!
short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}

OK this is a start. fgets() will read a line from a file for you. Or if you
like you can roll your own.

void readline(char *str, int maxlen, FILE *file)
{
int c;
while ( ( c = fgetc( file ) ) != EOF )
{
maxlen--;
if(maxlen <= 0)
break;
if ( c == '\n' )
break;
*str++ = (char) c;
}
/* add terminating NUL */
*str = 0;
}

(You might want to think about handling error conditions).

Once you've got your line into a string, you can write this function

/*
extract a substring.
in - input string.
out - pointer to output buffer.
start - start position
len - length of substring.
*/
void extract(const char *in, char *out, int start, int len)
{
}
Nov 14 '05 #6
Sharon wrote:

hi,

I want to extract a string from a file,
if the file is like this:
1 This is the string 2 3 4

how could I extract the string, starting from the 10th position (i.e. "T")
and extract 35 characters (including "T") from a file and then go to next
line?

I know how to go to next line but have no idea how to extract string
thank you for answering!

short c;

/* code for extract the string from file */

while ( ( c = fgetc( file ) ) != EOF )
{
if ( c == '\n' )
break;
}


This will sound like nit-picking but text files don't have strings in
them. Really. Strings are memory things. Lines are file things. Assuming
you have a file whose first line looks like your example, do something
like this..

char line[256]; /* some too-long number */
.... open the file, etc.
fgets(line, sizeof line, file);

This will read the line from the file and make a string out of it in
line[].

"1 This is the string 2 3 4\n"
012345678901234 567890123456789 012345678901
1 2 3 4
This is a string because fgets has placed a '\0' in line[41] just past
the '\n'. Note that 'T' is at line[10] but is the eleventh character,
not the tenth. Note also that there are not 35 characters on the line
after the 'T'.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #7
In article <bs***********@ news.hgc.com.hk >, sh************@ hotmail.com wrote:
"lallous" <la*****@lgwm.o rg> wrote:
If your read string was: "1 This is the string 2 3 4" you
can parse it using strncpy() as:

char str[100];
strncpy(str, line+10, 35);
str[35] = 0;

sorry, I don't understand
how to get the value of "line" ?
e.g. using functions like "fgetc( file)" ??


The common suggestion which is equivalent to the loop around fgetc() ideas
posted here is to use fgets() to get each line. For technical reasons one
might use a getInput()-style function instead, which you can find here:
http://www.pobox.com/~qed/userInput.html . So using a getInput function its
something like:

FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char * line;

while (!feof (fp)) {
line = NULL;
int len = fgetstralloc (&line, fp);
if (len > 10) {
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';

printf ("<<%s>>\n", substr);
}
free (line);
}
fclose (fp);
}

Otherwise if you just want to use fgets ... either life gets really really
difficult or you can implement a "truncated line" solution and hope for the
best:

#define MAX_LINE_SIZE (192)
FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char line [MAX_LINE_SIZE];
while (!feof (fp)) {
/* This will just screw up if you have a line of > 192
characters and fixing it is annoying. Also this
comment will be out of data when you change
MAX_LINE_SIZE. */
fgets (line, MAX_LINE_SIZE, fp);
if (strlen (line) > 10) {
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';
printf ("<<%s>>\n", substr);
}
}
fclose (fp);
}

Of course, if you wanted to do a completely incremental approach (whose ideas
are not really reusable as you try to solve more complex problems) then you
could just do this:

FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char str[36];
int s = 0;
int c;

while (EOF != (c = fgetc (fp)) {
if (c == '\n') {
str[s-10] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
if (s >= 10) {
if (s < 35 + 10) str[s-10] = c;
else if (s == 35 + 10) {
str[35] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
}
s++;
}
fclose (fp);
}

But this solution is a little bit complicated and may need some debugging to
make sure it works properly. Documenting it might be a little difficult as
well.

Another expressive way of doing this is to use a string library which is likely
to contain useful facilities for this purpose. One example is to use "the
better string library" (http://bstring.sf.net):

FILE * fp = fopen ("name_of_file. txt", "rb");
bstring b, s;

if (fp) {
while (!feof (fp)) {
s = bmidstr (b = bgets ((bNgetc) fgetc, fp, '\n'), 10, 35);
printf ("<<%s>>\n", s->data);
bdestroy (b);
bdestroy (s);
}
fclose (fp);
}

which is probably the easiest solution.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #8
On Tue, 23 Dec 2003 03:11:04 GMT, qe*@pobox.com (Paul Hsieh) wrote:
<snip>
The common suggestion which is equivalent to the loop around fgetc() ideas
posted here is to use fgets() to get each line. For technical reasons one
might use a getInput()-style function instead, which you can find here:
http://www.pobox.com/~qed/userInput.html . So using a getInput function its
something like:

FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char * line;

while (!feof (fp)) {
line = NULL;
int len = fgetstralloc (&line, fp);
if (len > 10) {
I haven't looked at your version of getline, but I hope here it is
returning a value <= 10, probably < 0 (or 1?), for EOF or I/O error.
If an input error occurs, which is admittedly unlikelyl if that name
accesses a disc file as is likely, this loop will run forever;
fgetstralloc() will keep failing, while !feof(fp) remains true.
You should test ferror(fp) also, and might as well put the tests at
the bottom with do ... while() instead of while() ....
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';

printf ("<<%s>>\n", substr);
Aside: if the *only* thing you want to do with a substring is *printf
it, you can just use %.35s with line+10. The OP didn't say that is
what she wanted, although 'extract' *might* mean that.
}
free (line);
}
Curiosity: why is len, whose value is only meaningful per line, local
to the loop body, while line, whose value you make meaningful only per
line although I'm guessing it *could* be otherwise, not?
fclose (fp);
}

Otherwise if you just want to use fgets ... either life gets really really
difficult or you can implement a "truncated line" solution and hope for the
best:

#define MAX_LINE_SIZE (192)
FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char line [MAX_LINE_SIZE];
while (!feof (fp)) {
/* This will just screw up if you have a line of > 192
characters and fixing it is annoying. Also this
comment will be out of data when you change
MAX_LINE_SIZE. */
fgets (line, MAX_LINE_SIZE, fp);
if (strlen (line) > 10) {
The contents of line are undefined if fgets() fails due to I/O error;
in theory this could crash, although in practice it will probably just
be garbage or the last line. Infinitely, as for the one above.
char substr[36];
strncpy (substr, line + 10, 35);
substr[35] = '\0';
printf ("<<%s>>\n", substr);
}
}
fclose (fp);
}

Of course, if you wanted to do a completely incremental approach (whose ideas
are not really reusable as you try to solve more complex problems) then you
could just do this:

FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char str[36];
int s = 0;
int c;

while (EOF != (c = fgetc (fp)) {
if (c == '\n') {
str[s-10] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
if (s >= 10) {
if (s < 35 + 10) str[s-10] = c;
else if (s == 35 + 10) {
str[35] = '\0';
printf ("<<%s>>\n", str);
s = 0;
}
}
s++;
}
fclose (fp);
}
Fails catastrophicall y on an input line less than 10 characters, or
between 45 and (I'm pretty sure) 53 and so on; off-by-one in lines
after the first; produces multiple pieces from lines longer than 53
characters, which I don't think was desired; produces no output at all
from a last (or only) line unterminated by \n on implementations which
support that.
But this solution is a little bit complicated and may need some debugging to
make sure it works properly. Documenting it might be a little difficult as
well.
Uh, er, yeah :-)
Another expressive way of doing this is to use a string library which is likely
to contain useful facilities for this purpose. One example is to use "the
better string library" (http://bstring.sf.net):

FILE * fp = fopen ("name_of_file. txt", "rb");
bstring b, s;

if (fp) {
while (!feof (fp)) {
s = bmidstr (b = bgets ((bNgetc) fgetc, fp, '\n'), 10, 35);
Again assuming your routines are safe for error or EOF, and again
continues looping forever on error, unless your bgets() exit's or
longjmp's. (And assuming you're not on my rare TNS1-equivalent where
FILE* is different from void* <G>.)
printf ("<<%s>>\n", s->data);
bdestroy (b);
bdestroy (s);
}
fclose (fp);
}

which is probably the easiest solution.


- David.Thompson1 at worldnet.att.ne t
Nov 14 '05 #9
Dave Thompson <da************ *@worldnet.att. net> wrote:
On Tue, 23 Dec 2003 03:11:04 GMT, qe*@pobox.com (Paul Hsieh) wrote:
<snip>
The common suggestion which is equivalent to the loop around fgetc() ideas
posted here is to use fgets() to get each line. For technical reasons one
might use a getInput()-style function instead, which you can find here:
http://www.pobox.com/~qed/userInput.html . So using a getInput function
its something like:

FILE * fp = fopen ("name_of_file. txt", "rb");
if (fp) {
char * line;

while (!feof (fp)) {
line = NULL;
int len = fgetstralloc (&line, fp);
if (len > 10) {
I haven't looked at your version of getline, but I hope here it is
returning a value <= 10, probably < 0 (or 1?), for EOF or I/O error.


Its written on top of fgetc(), so an error or EOF will be detected and
unified to mean the same thing causing the input line to terminate at
that point.
If an input error occurs, which is admittedly unlikelyl if that name
accesses a disc file as is likely, this loop will run forever;
fgetstralloc() will keep failing, while !feof(fp) remains true.
You should test ferror(fp) also,


Fine, so replace my feof() with (feof(fp) || ferror(fp)). Besides a
mindless bug for a mindless solution, you quoted my entire longish
post just to point this out three more times -- go look up the word
"constructi ve" as it relates to the phrase "constructi ve criticism"
(keeping in mind that the OP was trying the learn something, other
than the existence of hardware that became obsolete long before the
existence of USENET.)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #10

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

Similar topics

6
10509
by: Mohammad-Reza | last post by:
Hi I want to extract icon of an exe file and want to know how. I look at the MSDN and find out that I can use ExtractIconEx() Windows API but in there are some changes to that api in c# I made those changes like this : public static extern uint ExtractIconEx( string szFile,
5
17084
by: Bill | last post by:
Is there any way to programatically extract a cab file using C#? -- Bill Larson
7
7622
by: erikcw | last post by:
Hi all, I'm trying to extract zip file (containing an xml file) from an email so I can process it. But I'm running up against some brick walls. I've been googling and reading all afternoon, and can't seem to figure it out. Here is what I have so far. p = POP3("mail.server.com")
2
2082
by: vishwa Ram | last post by:
Hi Dears, I want vb code, for extract xml file from Indesign. Thanks, vishwa Ram.
4
1533
by: WT | last post by:
Hello, I am using themes and have seral themes for my site, user can choose it from a list then it is applyed to all pages by program. Problem is that some compoinent we use does not support themes and we must provide it with a file name. Is it possible , knowing the skinid to extract the file name associated in the current theme ? Thanks in advance forhelp.
3
3923
by: learningvbnet | last post by:
Hi, I am trying to extract zipped files using Winzip in my VB.net application and I ran into 2 stone walls. 1. How do you handle file names with spaces. See psiProcess.Arguments For example "My Data file Apr2007.zip"? In the example below, the parameter pZippedFile contains the file name with spaces and the pExtractFolder contains the folder where it should be extracted. 2. Is there anyway to get the extracted...
1
1524
by: josephtys86 | last post by:
203.114.10.66 - - "GET /stat.gif? stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43...
1
2720
by: Edwin.Madari | last post by:
from each line separate out url and request parts. split the request into key-value pairs, use urllib to unquote key-value pairs......as show below... import urllib line = "GET...
5
1810
by: moroccanplaya | last post by:
i got a program that creates a file then adds a file on top of that file so how would i go on and extract this file? here is my code.
0
8585
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8517
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8934
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8770
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6441
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4309
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1940
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.