473,795 Members | 3,063 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

read writte to file


#include <stdio.h>

int main( void ){
char cQuit = 'a';
char cKommando , artistNamn[80] , skivansNamn[80] , cChar;
int cK ;
FILE *pekaFile;

printf( "l - for read file\n");
printf( "s - for writte file\n");
printf( "q - quite\n");

while( cQuit != 'q' ){

if( cKommando == 'l' || cKommando == 'L' ){

if( ( pekaFile = fopen( "registret.txt" ,"r" ) ) == NULL )
//works just fine
{
printf("Can't open file \n" );
exit(1);
}
printf( "\nCD register \n\n" );
printf( "ARTIST NAMN \n" );
do
{
cChar = fgetc( pekaFile );
putchar( cChar );
} while ( cChar != EOF);
fclose( pekaFile );
printf( "\n");
}
else if( cKommando == 's' || cKommando == 'S' ){

printf("Type artist name: ");
scanf("%s",arti stNamn); //<<<=problem here can't input more
that one word in string
printf("Type cd titel: ");
scanf("%s",skiv ansNamn);//<<<=problem here can't input more
that one word in string

if( ( pekaFile = fopen("registre t.txt","a" ) ) == NULL )
{
printf( "Can't open file \n" );
exit( 1 );
}

fprintf( pekaFile, "%s %s\n", artistNamn, skivansNamn );
//<<<= or here can't writte more that one word in string?!

fclose( pekaFile );
}
printf("Command me: "); //<<<== gets printed 2 times, why?
cQuit = cKommando;
cK = getchar();
cKommando = (char)cK;
}
}/* END main */
--

Thanx in advance
_______________ _________
BTW. I know my english is not best in the word, so please stop bugging me
about my spelling. And yes Iam sorry you don't understand what I mean, but
there is no point to yell at me. Have a nice day.

Nov 14 '05 #1
9 1738
Carramba wrote:

#include <stdio.h>

int main( void ){
char cQuit = 'a';
char cKommando , artistNamn[80] , skivansNamn[80] , cChar;
It is usually better not to use magic numbers, i.e.
#define NAMELEN 80
and
char artistNamn[NAMELEN + 1], ....
are usually better (the +1 is for the string terminator '\0'
and stems from the fact that there are often comparisons against
the string length; for this, one can use NAMELEN).
int cK ;
FILE *pekaFile;

printf( "l - for read file\n");
printf( "s - for writte file\n");
printf( "q - quite\n");

while( cQuit != 'q' ){

if( cKommando == 'l' || cKommando == 'L' ){
You use cKommando without having initialised it or assigned to it.

if( ( pekaFile = fopen( "registret.txt" ,"r" ) ) == NULL )
//works just fine
{
printf("Can't open file \n" );
exit(1);
You call exit without having included <stdlib.h>; moreover, you
use an at best implementation defined argument value.
The standard gives you 0, EXIT_SUCCESS and EXIT_FAILURE.
}
printf( "\nCD register \n\n" );
printf( "ARTIST NAMN \n" );
do
{
cChar = fgetc( pekaFile );
Your are assigning the int return value to a char variable.
This may well lead to your losing information or wading into
the realm of undefined behaviour.
Use int as type for single characters:
int cChar
putchar( cChar );
} while ( cChar != EOF);
This is the wrong way round.
EOF is usually not representable by char cChar (and should not
be output as it is no character but an indicator value).
Use
while ((cChar = fgetc(pekaFile) ) != EOF)
{
putchar(cChar);
}
This works always if cChar is of type int.

Note: The macro getc can replace the call to fgetc() in this
case; getc is often more efficient.
fclose( pekaFile );
printf( "\n");
}
else if( cKommando == 's' || cKommando == 'S' ){
once again, cKommando is not initialised the first time.

printf("Type artist name: ");
scanf("%s",arti stNamn); //<<<=problem here can't input
more that one word in string
printf("Type cd titel: ");
scanf("%s",skiv ansNamn);//<<<=problem here can't input
more that one word in string
Note: Using scanf() without checking the return value almost
always is a sign that you did not give enough thought.
You can read your line using fgets() or Pop's device(*) (whichever
is more to your liking) or make use of one function out of a
host of nonstandard replacements -- neither fgets() nor scanf()
are well designed.
In your above invocation, you also are inviting trouble for overly
long input (->buffer overflow).

if( ( pekaFile = fopen("registre t.txt","a" ) ) == NULL )
{
printf( "Can't open file \n" );
exit( 1 );
}

fprintf( pekaFile, "%s %s\n", artistNamn, skivansNamn );
//<<<= or here can't writte more that one word in string?!

fclose( pekaFile );
}
During program development, it often is a good idea to catch
or at least trace the impossible case, i.e.

else {
fprintf(stderr, "cKommando was neither l/L nor s/S!\n");
}

In this case, it may not necessarily have enlightened you...
printf("Command me: "); //<<<== gets printed 2 times, why?
cQuit = cKommando;
cK = getchar();
You are mixing scanf() und getchar() for input from stdin.
This is not a good idea, as scanf() leaves "trash" on the input.
Please read the comp.lang.c FAQ on scanf() and getchar() and
their proper use.
BTW: Usually, one reads or skims the FAQ _before_ posting.
cKommando = (char)cK;
}
No int return.
}/* END main */


(*) Pop's Device: search the comp.lang.c archives with groups.google.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
Carramba wrote:

#include <stdio.h>

int main( void ){
char cQuit = 'a';
char cKommando , artistNamn[80] , skivansNamn[80] , cChar;
int cK ;
FILE *pekaFile;

printf( "l - for read file\n");
printf( "s - for writte file\n");
printf( "q - quite\n");

while( cQuit != 'q' ){

if( cKommando == 'l' || cKommando == 'L' ){

if( ( pekaFile = fopen( "registret.txt" ,"r" ) ) == NULL )
//works just fine
{
printf("Can't open file \n" );
exit(1);
}

printf( "\nCD register \n\n" );
printf( "ARTIST NAMN \n" );
do
{
cChar = fgetc( pekaFile );
putchar( cChar );
} while ( cChar != EOF);
fclose( pekaFile );
printf( "\n");
}

else if( cKommando == 's' || cKommando == 'S' ){

printf("Type artist name: ");
scanf("%s",arti stNamn); //<<<=problem here can't input more
that one word in string
printf("Type cd titel: ");
scanf("%s",skiv ansNamn);//<<<=problem here can't input more
that one word in string

if( ( pekaFile = fopen("registre t.txt","a" ) ) == NULL )
{
printf( "Can't open file \n" );
exit( 1 );
}

fprintf( pekaFile, "%s %s\n", artistNamn, skivansNamn );
//<<<= or here can't writte more that one word in string?!

fclose( pekaFile );
}
printf("Command me: "); //<<<== gets printed 2 times, why?
cQuit = cKommando;
cK = getchar();
cKommando = (char)cK;
}
}/* END main */


/* BEGIN new.c */

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

#define a_LEN 79
#define s_LEN 79
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
char a_Namn[a_LEN + 1], s_Namn[s_LEN + 1];
int cK, rc;
FILE *pekaFile;

puts("l - for read file");
puts("s - for writte file");
puts("q - quite");
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar();
while (cK != 'q') {
if (cK == 'l' || cK == 'L') {
pekaFile = fopen("registre t.txt", "r");
if (pekaFile == NULL) {
puts("Can't open file");
exit(EXIT_FAILU RE);
}
puts("\nCD register\n");
puts("a_ NAMN");
do {
cK = fgetc(pekaFile) ;
putchar(cK);
} while (cK != EOF);
fclose(pekaFile );
putchar('\n');
} else {
if (cK == 's' || cK == 'S') {
fputs("Type a name: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*a_Namn = '\0';
}
fputs("Type cd titel: ", stdout);
rc = scanf("%" xstr(s_LEN) "[^\n]%*[^\n]", s_Namn);
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*s_Namn = '\0';
}
pekaFile = fopen("registre t.txt","a");
if (pekaFile == NULL) {
fputs("Can't open file \n", stderr);
exit(EXIT_FAILU RE);
}
fprintf(pekaFil e, "%s %s\n", a_Namn, s_Namn);
fclose(pekaFile );
}
}
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar();
}
return 0;
}

/* END new.c */
--
pete
Nov 14 '05 #3
pete wrote:
puts("a_ NAMN");


Should be:

puts("ARTIST NAMN");

--
pete
Nov 14 '05 #4
oh man thats rocks! thanx, I jus have few questions and I hope you don't
mind to answer them

On Tue, 07 Jun 2005 23:04:11 +0200, pete <pf*****@mindsp ring.com> wrote:
/* BEGIN new.c */
#include <stdio.h>
#include <stdlib.h>
#define a_LEN 79
#define s_LEN 79
#define str(x) # x <= what is it? and why?
#define xstr(x) str(x) <= what is it? and why?
int main(void)
{
char a_Namn[a_LEN + 1], s_Namn[s_LEN + 1];
int cK, rc;
FILE *pekaFile;
puts("l - for read file");
puts("s - for writte file");
puts("q - quite");
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar(); why do you double getchar(); ?
while (cK != 'q') {
if (cK == 'l' || cK == 'L') {
pekaFile = fopen("registre t.txt", "r");
if (pekaFile == NULL) {
puts("Can't open file");
exit(EXIT_FAILU RE);
}
puts("\nCD register\n");
puts("a_ NAMN");
do {
cK = fgetc(pekaFile) ;
putchar(cK);
} while (cK != EOF);
fclose(pekaFile );
putchar('\n');
} else {
if (cK == 's' || cK == 'S') {
fputs("Type a name: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);
don't realy understand what are you doing here ( in line above )? I se
that you are reading input, but could you explaine more?
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*a_Namn = '\0';
}
fputs("Type cd titel: ", stdout);
rc = scanf("%" xstr(s_LEN) "[^\n]%*[^\n]", s_Namn);
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*s_Namn = '\0';
}
pekaFile = fopen("registre t.txt","a");
here file ll by created if it not exists, is there any reason for error
messege?
if (pekaFile == NULL) {
fputs("Can't open file \n", stderr);
exit(EXIT_FAILU RE);
}
fprintf(pekaFil e, "%s %s\n", a_Namn, s_Namn);
fclose(pekaFile );
}
}
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar();
}
return 0;
}
/* END new.c */


--

Thanx in advance
_______________ _________
BTW. I know my english is not best in the word, so please stop bugging me
about my spelling. And yes Iam sorry you don't understand what I mean, but
there is no point to yell at me. Have a nice day.

Nov 14 '05 #5
Carramba <no****@note.co m> wrote:
rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);


don't realy understand what are you doing here ( in line above )? I se
that you are reading input, but could you explaine more?


A line of input is read into the buffer a_Namn.

Notice that a_Namn has a size and you should never write more characters
into a buffer than it can hold. So scanf can be told to at most read a
certain numer of characters. Say if you want to read a word and have a
buffer that can hold 10 characters you'll do something like "%9s". So
scanf will read 9 characters and finish the string with the obligatory
nul-character.
If you don't just want to read a word (a string of characters that
ends at the next white space) you can go for "%[^\n]" which tells scanf
to read any characters that are not newline-characters into the given
buffer. To limit the amount of characters read you can go with
"%99[^\n]" for example. Now this holds teh risc that when you at some
time in development of your program decrease the size fo the buffer from
100 characters to say 50 characters, and don't change the
scanf-format-string to 49 instead of 99, overflow may occure. This is
why many programmers try to calculate the size of the buffers in use
automagically. And also want to do this with scanfs and such.
How could you do this with scanf?
Well as you can see in the above line of code.
a_LEN tells us the size we use literally. Since scanf expects the size
to be passed in a string we need to produce a string of the value a_LEN
represents. The xstr() macro-trick does this.
Now all you need to know ist that in C "strings" " are" " concatenated"
automatically. (So the compiler makes "strings are concatenated" from
the above). I hope this clears up some things.
pekaFile = fopen("registre t.txt","a");


here file ll by created if it not exists, is there any reason for error
messege?


You can't rely on a success of fopen. It may fail for various reasons.

--
Z (zo**********@w eb.de)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Nov 14 '05 #6
yes thanx got it know, but still have few more questions:
On Tue, 07 Jun 2005 23:04:11 +0200, pete <pf*****@mindsp ring.com> wrote:

/* BEGIN new.c */

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

#define a_LEN 79
#define s_LEN 79
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
char a_Namn[a_LEN + 1], s_Namn[s_LEN + 1];
int cK, rc;
FILE *pekaFile;
puts("l - for read file");
puts("s - for writte file");
puts("q - quite");
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar();
while (cK != 'q') {
if (cK == 'l' || cK == 'L') {
pekaFile = fopen("registre t.txt", "r");
if (pekaFile == NULL) {
puts("Can't open file");
exit(EXIT_FAILU RE);
}
puts("\nCD register\n");
puts("a_ NAMN");
do {
cK = fgetc(pekaFile) ;
putchar(cK);
} while (cK != EOF);
fclose(pekaFile );
putchar('\n');
} else {
if (cK == 's' || cK == 'S') {
fputs("Type a name: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);
if (!feof(stdin)) {
getchar();
}
what is going on here? if (rc != 1) {
*a_Namn = '\0';
}
do I get it right that the '\0' character ll by atendet to string
a_Namn if input have succedet?
fputs("Type cd titel: ", stdout);
rc = scanf("%" xstr(s_LEN) "[^\n]%*[^\n]", s_Namn);
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*s_Namn = '\0';
}
pekaFile = fopen("registre t.txt","a");
if (pekaFile == NULL) {
fputs("Can't open file \n", stderr);
exit(EXIT_FAILU RE);
}
fprintf(pekaFil e, "%s %s\n", a_Namn, s_Namn);
fclose(pekaFile );
}
}
fputs("Command me: ", stdout);
fflush(stdout);
cK = getchar();
getchar();
}
return 0;
}

/* END new.c */


--

Thanx in advance
_______________ _________
BTW. I know my english is not best in the word, so please stop bugging me
about my spelling. And yes Iam sorry you don't understand what I mean, but
there is no point to yell at me. Have a nice day.

Nov 14 '05 #7
Carramba wrote:

oh man thats rocks! thanx,
I jus have few questions and I hope you don't
mind to answer them

On Tue, 07 Jun 2005 23:04:11 +0200,
pete <pf*****@mindsp ring.com> wrote:

int cK, rc; cK = getchar(); getchar();

why do you double getchar(); ?


To eat the '\n' from the Enter key.
Note that cK is of type int and not char,
to match the return type of getchar.
fputs("Type a name: ", stdout);
fflush(stdout);
rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);


don't realy understand what are you doing here
( in line above )? I se
that you are reading input, but could you explaine more?


Zorna Cutura explained it pretty good.
The idea, is to convert text lines into strings.
Text files and streams are made of lines.
A line is like a string, except that a line is
teminated by a '\n' character,
and a string is terminated by a '\0' character.
if (!feof(stdin)) {
getchar();
}
if (rc != 1) {
*a_Namn = '\0';
}
fputs("Type cd titel: ", stdout);


There should be
fflush(stdout);
after that fputs.
--
pete
Nov 14 '05 #8
Carramba wrote:
#define a_LEN 79 #define str(x) # x
#define xstr(x) str(x) rc = scanf("%" xstr(a_LEN) "[^\n]%*[^\n]", a_Namn);


if (!feof(stdin)) {
getchar();
}
what is going on here?


getchar is eating the '\n' at the end of the text line.
The !feof is a little more complicated to explain,
but it is to also make this work for systems with a
non sticky end of file condition.
I don't really know too much about sticky vs non sticky,
except that systems are supposed to have sticky eof,
but some of them, don't.


if (rc != 1) {
*a_Namn = '\0';
}

do I get it right that the '\0' character ll by atendet to string
a_Namn if input have succedet?


rc is capable of having one of three different values at this point.
If rc equals 1, then there is a string in a_Namn.
If rc equals 0, then that means that the text line
had only a '\n' character and that there is no string in a_Namn.
If rc equals EOF, then you have an end of file condition
or some kind of error, and no string in a_Namn.

--
pete
Nov 14 '05 #9
pete wrote:
Zorna


So, I'm thinking to myself "Is Zoran going to notice that?"
and then "Yes, probably."
Sorry about that.

--
pete
Nov 14 '05 #10

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

Similar topics

10
5332
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
10
2289
by: ZafT | last post by:
Thanks in advance for any tips that might get me going in the right direction. I am working on a simple exercise for school that is supposed to use read to read a file (about 10 MB). I am supposed to change the buffer size and see how this affects the read time. In other words, the buffer is supposed to limit how much of the file gets read per call, and cause some change in speed. I am supposed to do the same with fread as well, but...
1
6771
by: cnu | last post by:
My program generates a log file for every event that happens in the program. So, I open the file and keep it open till the end. This is how I open the file for writing: <CODE> public CLogHandler() { this.m_fsLog = new FileStream(strTodaysLogFile, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read); this.m_swLog = new StreamWriter(this.m_fsLog);
4
2748
by: ESPN Lover | last post by:
Below is two snippets of code from MSDN showing how to read a file. Is one way preferred over the other and why? Thanks. using System; using System.IO; class Test { public static void Main()
8
23908
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
5
3306
by: lovecreatesbea... | last post by:
The condition at line 31 is added to check if the program finished to read the whole file. Is it needed and correct? Thank you. #include <fstream> #include <iostream> #include <string> using namespace std; int read(string filename, int last_pos) {
6
32921
by: Thomas Kowalski | last post by:
Hi, currently I am reading a huge (about 10-100 MB) text-file line by line using fstreams and getline. I wonder whether there is a faster way to read a file line by line (with std::string line). Is there some way to burst read the whole file and later "extract" each line? Thanks in advance, Thomas Kowalski
9
7389
by: flebber | last post by:
I was working at creating a simple program that would read the content of a playlist file( in this case *.k3b") and write it out . the compressed "*.k3b" file has two file and the one I was trying to read was maindata.xml . I cannot however seem to use the gzip module correctly. Have tried the program 2 ways for no success, any ideas would be appreciated. Attempt 1 #!/usr/bin/python
2
5458
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) OverflowError: long it too large to...
0
9519
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
10436
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10213
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
10163
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,...
0
10000
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7538
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
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
3
2920
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.