473,395 Members | 1,343 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,395 software developers and data experts.

FILE Operations

Can someone write a sample c code showing how one can find an instance of a
word or a char in a file (including opening and closing a file)? Thanks
Nov 14 '05 #1
13 1618
Steve wrote on 28/07/04 :
Can someone write a sample c code showing how one can find an instance of a
word or a char in a file (including opening and closing a file)? Thanks


This is going too far. You have to write the code yourself.

Hints: Open your C book.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

Nov 14 '05 #2
> Can someone write a sample c code showing how one can find an instance of
a
word or a char in a file (including opening and closing a file)? Thanks

Hi Steve,
This code lets you count the instances of a given char:
#include <stdio.h>
#include <string.h>
int main()
{
const char fileName[] = "fileName.txt";
const char toCount = 'f';

FILE* f = fopen(fileName, "r");
if(!f)
{
printf("File NOT found\n");
exit(0);
}

char s[100];
memset(s, '\0', 100);
int count = 0;
while (fgets(s, 100, f))
{
char * q = &s[0];
for(; *q != '\0'; q++)
{
if(*q == toCount)
count++;
}
printf("%s", s);/* to print each set of chars*/
}
memset(s, '\0', 100);
printf("You have %d \"%c's\"\n", count, toCount);
fclose(f);

return 0;
}


Nov 14 '05 #3
Please don't do other's home work...
They will not learn anything and they will tell their friends:

Just let comp.lang.c people do the homework!
Nov 14 '05 #4
Jackie wrote on 28/07/04 :

My corrections (-ed-)

/* -ed- reformatted */

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

/* -ed- was missing (exit()) */
#include <stdlib.h>

int main ()
{
const char fileName[] = "fileName.txt";
const char toCount = 'f';

FILE *f = fopen (fileName, "r");

if (!f)
{
printf ("File NOT found\n");
/* -ed-
Semantically incorrect. 0 means OK.
exit (0);
*/
exit (EXIT_FAILURE);

}

/* -ed- block added. Not all compilers are C99 */
{
char s[100];
int count = 0;

/* -ed- Useless. Removed
memset (s, '\0', 100);
*/
/* -ed- Help maintenance. Avoid redundant information...
while (fgets (s, 100, f))
*/
while (fgets (s, sizeof s, f))
{
char *q = &s[0];
for (; *q != '\0'; q++)
{
if (*q == toCount)
count++;
}
printf ("%s", s); /* to print each set of chars */
}

/* -ed- Useless. Removed
memset (s, '\0', 100);
*/
printf ("You have %d \"%c's\"\n", count, toCount);
}
fclose (f);

return 0;
}

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

Nov 14 '05 #5
This is in response to Emmanuel Delahaye's comments:
memset is needed to set the positions to zero otherwise for the 2nd, 3rd,
.... readings you'll mix it with prior readings. Plus, for printf you'll have
to end with '\0'. stdlib.h is NOT needed for NULL because NULL is actually
0. SO, (char *)0 in that context does the job of NULL and is even better.
Nov 14 '05 #6
Jackie wrote on 28/07/04 :
This is in response to Emmanuel Delahaye's comments:
memset is needed to set the positions to zero otherwise for the 2nd, 3rd,
... readings you'll mix it with prior readings.
So what? Unless it returns NULL, the fgets() functions makes a valid
string. Always.
Plus, for printf you'll have
to end with '\0'.
Done already by fgets().
stdlib.h is NOT needed for NULL because NULL is actually
0. SO, (char *)0 in that context does the job of NULL and is even better.


I was not concerned by NULL but by the prototype of exit() as
mentionned:

[quoting myself]
/* -ed- was missing (exit()) */
#include <stdlib.h>


--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

Nov 14 '05 #7

"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> wrote in message
news:mn***********************@YOURBRAnoos.fr...
Jackie wrote on 28/07/04 :
This is in response to Emmanuel Delahaye's comments:
memset is needed to set the positions to zero otherwise for the 2nd, 3rd, ... readings you'll mix it with prior readings.


So what? Unless it returns NULL, the fgets() functions makes a valid
string. Always.


Are you saying that fgets() sets all the positions to '\0' before writing to
the same array for subsequent readings? Assume we have char s[10] What if
your 1st line is "123456789" and the second line is "1234" You may not see
it with printf because printf stops as soon as it reaches '\0' but for the
second reading you still have some chars from the 1st because the 1st line
is longer.
Nov 14 '05 #8
Jackie wrote on 28/07/04 :
memset is needed to set the positions to zero otherwise for the 2nd, 3rd,
... readings you'll mix it with prior readings.
So what? Unless it returns NULL, the fgets() functions makes a valid
string. Always.


Are you saying that fgets() sets all the positions to '\0' before writing to
the same array for subsequent readings?


Certainely not. What the standard says is that a 0 is placed at the end
of the string pointed by the first parameter of fgets() when it doen't
return NULL.

Just reread your C-book.
Assume we have char s[10] What if
your 1st line is "123456789" and the second line is "1234" You may not see
it with printf because printf stops as soon as it reaches '\0' but for the
second reading you still have some chars from the 1st because the 1st line
is longer.


That's plain wrong:

1st line : {'1','2','3','4','5','6','7','8','9',\n}
2nd line : {'1','2','3','4'\n}<EOF>

1st read : {'1','2','3','4','5','6','7','8','9',0} -> "123456789"
2nd read : {'\n',0,'3','4','5','6','7','8','9',0} -> CRLF
3st read : {'1','2','3','4','\n',0,'7','8','9',0} -> "1234"CRLF

I admit that it's not very 'clean' specially if you track the string
with a debugger, but it works correctly and safely.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html

"C is a sharp tool"

Nov 14 '05 #9
"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> wrote in message
news:mn***********************@YOURBRAnoos.fr...
Jackie wrote on 28/07/04 :
Assume we have char s[10] What if
your 1st line is "123456789" and the second line is "1234" You may not
see it with printf because printf stops as soon as it reaches '\0' but
for the second reading you still have some chars from the 1st because
the 1st line is longer.
That's plain wrong:


No, it's perfectly correct, as you go on to show. But interpreting the array
of char as a string means ignoring everything after the first '\0', so any
"left over" chars simply don't matter.
1st line : {'1','2','3','4','5','6','7','8','9',\n}
2nd line : {'1','2','3','4'\n}<EOF>

1st read : {'1','2','3','4','5','6','7','8','9',0} -> "123456789"
2nd read : {'\n',0,'3','4','5','6','7','8','9',0} -> CRLF
3st read : {'1','2','3','4','\n',0,'7','8','9',0} -> "1234"CRLF

I admit that it's not very 'clean' specially if you track the string
with a debugger, but it works correctly and safely.


Depends on the debugger, I guess.

Alex
Nov 14 '05 #10
On Wed, 28 Jul 2004 10:15:32 GMT, "Steve" <st********@earthlink.net>
wrote:
Can someone write a sample c code showing how one can find an instance of a
word or a char in a file (including opening and closing a file)? Thanks

You will have to learn to do your own homework. If you have a problem,
give it your best try and post it here, and many readers will be glad
to help.

Of course, there is always someone (usually a newer group member) who
is willing to post a solution, as you see elsethread. Use his
contribution if you want, but don't expect a good grade - it's not
very good code.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #11
Emmanuel Delahaye <em***@yourbranoos.fr> spoke thus:
while (fgets (s, sizeof s, f))
{
char *q = &s[0];
for (; *q != '\0'; q++)
{
if (*q == toCount)
count++;
}
printf ("%s", s); /* to print each set of chars */
}


Why not let strchr do some of the work for you?

while( fgets(s,sizeof s,f) ) {
char *q;
for( q=strchr(s,toCount); q != NULL; q=strchr(q+1,toCount) )
count++;
printf( "%s\n", s );
}

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #12

"Jackie" <ja**********@earthlink.net> wrote

Are you saying that fgets() sets all the positions to '\0' before writing to the same array for subsequent readings? Assume we have char s[10] What if
your 1st line is "123456789" and the second line is "1234" You may not see
it with printf because printf stops as soon as it reaches '\0' but for the
second reading you still have some chars from the 1st because the 1st line
is longer.

fgets() will NUL-terminate the string it puts into your buffer. There may be
garbage left after the NUL, but this doesn't matter.

You will sometimes see professional programmers memsetting character buffers
to zero for added safety, but the general consensus is that this isn't
necessary.
Nov 14 '05 #13
>> Are you saying that fgets() sets all the positions to '\0' before writing
to
the same array for subsequent readings? Assume we have char s[10] What if
your 1st line is "123456789" and the second line is "1234" You may not see
it with printf because printf stops as soon as it reaches '\0' but for the
second reading you still have some chars from the 1st because the 1st line
is longer.

fgets() will NUL-terminate the string it puts into your buffer. There may be
garbage left after the NUL, but this doesn't matter.

You will sometimes see professional programmers memsetting character buffers
to zero for added safety, but the general consensus is that this isn't
necessary.


It is often useful for security and testing purposes to force the
unused portion of a character buffer to be set to nul characters
BEFORE WRITING THE BUFFER TO A FILE. First, the garbage after the
end of the string may be something sensitive you don't want recorded
in a file. Second, it is often useful for things such as regression
testing to ensure that the same input generates the same output.
And garbage rarely compresses as well as a block of nul characters.

Now, there are arguments against writing structures containing
character buffers to a file: the padding isn't portable, and it
takes up more space than just writing the string. There's also all
the integer size and endian issues if the structure has members
other than character arrays. On the other hand, seeking to a
specific structure and updating it in place is possible (and possibly
MUCH faster than re-writing the whole file), and a file load/dump
program can handle issues of moving the data to a different system.

Gordon L. Burditt
Nov 14 '05 #14

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

Similar topics

10
by: Yang Li Ke | last post by:
Hi guys! I have some datas that I must check everytime a visitor comes to my site What is better to do: 1- Read data from a file or 2- Read data from a mysql db Thank you
5
by: Shu-Hsien Sheu | last post by:
Hi, Does the seek method would close the file object after using a for loop? My program looks like this: f = open('somefile', 'r') for lines in f: some operations f.seek(0)
3
by: Peter | last post by:
Hello, Two newbie questions: 1) I have a javascript file with a function in it. From this function I want to access a variable in another javascript file -which is not inside a function. I...
3
by: Scott Brady Drummonds | last post by:
Hello, all, My most recent assignment has me working on a medium- to large-sized Windows-based C++ software project. My background is entirely on UNIX systems, where it appears that most of my...
2
by: Eat_My_Shortz | last post by:
I'm trying to interoperate between file IO operations, on an open file, between unmanaged C++ code and Managed C++, using the .NET framework. Basically, at present, I have a C-style FILE* object,...
11
by: Jeevan | last post by:
Hi, I have some data which I am getting from a socket. I am currently storing the data in an array (so that future reading of the data will be fast as it will be in RAM instead of hard disk)....
0
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen....
9
by: Julien Biezemans | last post by:
Hi! Here is the problem: I'd like to restrict local filesystem stream operations to one directory just like a root jail. fopen('/file.bin') would actually open /some/path/file.bin. One goal...
5
by: MC | last post by:
I've been using the ASP.NET ad rotator for some time and have been asked to track the hits and click thrus, The solution that seemed obvious to me was to extend the existing control to record the...
0
by: tabassumpatil | last post by:
Please send the c code for: 1.STACK OPERATIONS : Transfer the names stored in stack s1 to stack s2 and print the contents of stack s2. 2.QUEUE OPERATIONS : Write a program to implement...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
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
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...
0
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...
0
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...

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.