GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 09-Feb-2010, 09:21
filevictim filevictim is offline
New Member
 
Join Date: Feb 2010
Posts: 4
filevictim is on a distinguished road

Create a text file


hi, i have just joined the forums. I have some experiance in C programming and just started learning files in C by myself. I wrote this following C code to create a text file and display back the text in the file i have initially created.
I know it has a lot of mistakes, the control gets struck at the line:
putc(ch,fp);
please point out my mistakes, thanx in advance.

CPP / C++ / C Code:
#include<stdio.h>
#include<conio.h>

void main()
{
FILE* fp;
char fname[30];
int ch;
clrscr();
printf("enter the filename\n");
scanf("%s",fname);
fp=fopen(fname,"w");
printf("enter the text\n");
while(ch!=EOF)
{
scanf("%d",&ch);
putc(ch,fp);
}
fclose(fp);
printf("now we shal open our created file and see what it has\n");
fp=fopen(fname,"r");
ch=getc(fp);
while(ch!=EOF)
{
printf("%d",ch);
ch=getc(fp);
}
getch();
}
Last edited by LuciWiz : 10-Feb-2010 at 10:05. Reason: Please insert your C code between [cpp] & [/cpp] tags
  #2  
Old 09-Feb-2010, 13:50
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,496
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Create a text file


Quote:
Originally Posted by filevictim
...create a text file and display back ...

One way:

Use getchar() to read characters from stdin and then use putc() to send them to the output file.

Note that for many (most?) Windows compilers you have to enter Ctrl-Z to indicate EOF from the console. Linux gcc and gcc/cygwin ports to Windows use Ctrl-D for EOF from the console.


Regards,

Dave
  #3  
Old 10-Feb-2010, 04:10
filevictim filevictim is offline
New Member
 
Join Date: Feb 2010
Posts: 4
filevictim is on a distinguished road

Re: Create a text file


yaa, modified it, now i have
while(ch!=EOF)
{
ch=getchar();
putc(ch,fp);
}

but the rest of the code below that has problem
i can't display back the file. thnks for ur reply.
  #4  
Old 10-Feb-2010, 07:45
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,496
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Create a text file


Quote:
Originally Posted by filevictim
...
i can't display back the file....

Are you saying that it doesn't exit the input loop? Or are you saying that it displays something other than what you expected? Does it create the file that you designated? Do the contents of that file differ from your expectations? Or what?

When asking for help for a particular problem my advice is: Be specific!

Also: Instead of making your code show up in the almost-unreadable-on-some-monitors dark orange, many (most?) of us would really appreciate if you would use code tags as described in the Guidelines for posting requests for help

Specifically:

Put the following before the first line of code:
[c]

Put the following after the last line of code:
[/c]

Then your code shows in a nice monospace font (so that spacing and indentation are preserved), and C syntax elements are highlighted in colors that most of us can actually see.

Regards,

Dave
  #5  
Old 11-Feb-2010, 05:22
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 350
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Create a text file


Quote:
Originally Posted by davekw7x
Then your code shows in a nice monospace font (so that spacing and indentation are preserved), and C syntax elements are highlighted in colors that most of us can actually see.

...and are accustomed to seeing in code editors and consoles.


MxB
  #6  
Old 12-Feb-2010, 00:23
filevictim filevictim is offline
New Member
 
Join Date: Feb 2010
Posts: 4
filevictim is on a distinguished road

Re:create a text file


thanx for replying again, i shall be more specific this time

The control is exiting the input loop, i have checked that by putting some printf statements after the input loop and they are appearing on the screen too. Also, i can open the files i have created in command prompt. So, i am sure the program till the input loop is fine.
Please look at the following modification i have made to the code to highlight the problem:
CPP / C++ / C Code:
while(ch!=EOF)
{
ch=getchar();
putc(ch,fp);
}
printf("*******************************************************\n");
printf("now we shal open our created file and see what it has\n");
printf("enter the file name\n");
gets(fname);
fp=fopen(fname,"r");
if(fp==NULL)
printf("can't open the file\n");
printf("*********************************************\n");
ch=getc(fp);

the rest of the program is as it was in the first post.
the output is as follows:
CPP / C++ / C Code:
enter the file name
file
enter the text
flskfjlkdjflaksdksjfhbksjhfkajhfkajhf^Z
*******************************************************
now we shal open our created file and see what it has
enter the file name
*********************************************

All the printf statements execute ine by one as soon as i press enter after ctrl+z
i could not input the filename. and after last line,when i press a key, it takes me back to the editor console. problem is, it's not takin the file name input.
  #7  
Old 12-Feb-2010, 00:32
filevictim filevictim is offline
New Member
 
Join Date: Feb 2010
Posts: 4
filevictim is on a distinguished road

Re: Create a text file


sorry, there is also this slight modification in the last while loop of the program.
i am using putchar instead of printf
:
CPP / C++ / C Code:
while(ch!=EOF)
{
putchar(ch);
ch=getc(fp);
}
getch();
}
  #8  
Old 12-Feb-2010, 01:30
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,377
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: Create a text file


Every time you read a single character from the keyboard using getchar() you are leaving the \n in the buffer for the next read.

Please format your code. It is still hard to follow.

Also, see this about gets()
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #9  
Old 12-Feb-2010, 05:16
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 350
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Create a text file


Quote:
Originally Posted by filevictim
hi, i have just joined the forums. I have some experiance in C programming and just started learning files in C by myself. I wrote this following C code to create a text file and display back the text in the file i have initially created.

CPP / C++ / C Code:
#include<stdio.h>
#include<conio.h>

void main()

Your main function should return an int and you should avoid using conio.h if possible. I also recommend using more whitespace:

CPP / C++ / C Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>

int main()
{
    char c = 0;
    char buf[BUFSIZ] = {0};
    int fd;

    struct stat fs;

    printf("Input name of file to be created: ");
    fgets(buf, sizeof(buf), stdin);
    buf[strlen(buf) - 1] = '\0';

    fd = open(buf, O_RDWR | O_CREAT);
    if(fd >= 0)
    {
	printf("File %s successfully opened.\n\nEnter data: \n", buf);
	while(c != '\n')
	{
	    if(read(STDIN_FILENO, &c, sizeof(c)) > 0)
	    {
		if(write(fd, &c, sizeof(c)) < 0)
		{
		    printf("Error # %d when writing to file descriptor %d identified as %s\n", errno, fd, buf);
		    break;
		}
	    }
	}
	if(fstat(fd, &fs) != 0)
	{
	    printf("Error # %d while obtaining status of file descriptor %d identified as %s\n", errno, fd, buf);
	}
	else
	{
	    printf("Wrote %u bytes to file descriptor %d identified as %s\n", (unsigned)fs.st_size, fd, buf);
	}
	if(close(fd))
	{
	    printf("Error # %d encountered while closing file descriptor %d identified as %s\n", errno, fd, buf);
	}
	else
	{
	    printf("File %s successfully closed.\n", buf);
	}
    }
    else
    {
	printf("Error opening file named %s\nCheck the full path and permissions before trying again.\n", buf);
    }
    return 0;
}


Output:

Code:
bash-3.2$ gcc -g -Wall -W -Wextra -pedantic -o filevic filevic.c bash-3.2$ ./filevic Input name of file to be created: bogus File bogus successfully opened. Enter data: abcdefghijklmnopqrstuvwxyz Wrote 27 bytes to file descriptor 4 identified as bogus File bogus successfully closed. bash-3.2$ ls -la bogus -rwxr----- 1 mxb staff 27 Feb 12 00:04 bogus bash-3.2$ cat bogus abcdefghijklmnopqrstuvwxyz


MxB
  #10  
Old 13-Feb-2010, 05:06
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Regular Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 350
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Create a text file


Quote:
Originally Posted by WaltP
Please format your code. It is still hard to follow.

Perhaps some recommended modifications to that article?

...like suggesting that jamming the #include<stdio.h> together should be avoided?

The format "I use" shows a contradiction to the recommended whitespace usage:

int i,j;
for (i=1; i<5; i++)

...unless this is one of those cases where "and in many cases between the operators" does not apply.

...and main does not explicitly return an int. A compiler warning in waiting?

Under the "Indentation" section:

"The biggest aid to understanding."

...is not a complete sentence.

The "bottom line" contradicts the Whitesmiths style example shown.

"Some free, some shareware."

...is not a complete sentence.

"Small but useful."

...probably needs some help, too. "Small" is usually an adjective and is intended to describe the code that precedes it, so it is not a complete sentence as (apparently) intended. Perhaps as an interjection it would work?

Small, but useful!

The problem is that "what is small" is the difference between the first example that uses whitespace and the second example, that pushes everything together. But, we have to go all the way back to the section heading to relate the adjective to the noun that it modifies. That is a recipe for confusing readers--particularly those who are not native English readers/speakers. In general, avoiding common speaking habits in writing will likely aid readers in understanding if not too-terse wording is used. "Speaking" to your readers as if they are your friends is usually a good choice, but when "speaking" to a global audience of varied friends, one should lean toward clearer presentation of content and less "familiar voice" that is more difficult for others to follow.

I once worked with a Chinese mathematician. He embodied all things "geek." He was a nice guy, but definitely lived as a "full time" geek. He had incredibly bad dandruff, nearly always walked around with his fly down, wore plaid with stripes, blue socks with brown sandals and had very severe halitosis. He even had the "Coke bottle bottom" glasses. Counter-balancing these attributes was his ability to create amazingly good algorithms in exceptionally poor (visually) code. His code was a pure reflection of his exterior AND his interior! Very brilliant, but not incredibly "presentable."

This guy could read English rather well. He was practically incapable of speaking or writing something of use to anyone else, except for ugly, but effective C code without a single comment ever. I once found a "comment" that took out a variable declaration that apparently he decided that he didn't need any more. I also found a one-line declaration that used 47 one-character named variables--all of them doubles.

I used to work with him to make his code more readable. He seemed fascinated that I could "straighten out" his code to make it arguably "more presentable." I would sit with him asking him what things were what in his code and then commented them and pulled from him notations about the complexities that spun around inside his head. He was amazed that I always greeted him with offerings of Altoids or chewing gum as he seemed to find such gestures overwhelmingly generous. One day he brought me a pack of Chinese gum as a symbol of friendship and repayment of my previous generosity. I'm sure that it was an extravagant purchase on his part. I can't imagine what he was paid, but peanuts may have been an improvement!

The guy had a black leather belt that was perhaps a foot or so too long and he literally tied it about his none too-thin waist. I suspected that he shopped at the Goodwill store before they placed the items on display; rather, he pulled them from the incoming bin of jumbled up articles at bulk rates. I can't imagine that he ever laundered any thing that he wore. The underarm stains in his shirts looked like the rings of Saturn on a clear day.

I secretly hoped that someday he would meet some incredibly hot Chinese model who would bathe him and buy him coordinated "fashions" and comb his hair in exchange for the likely fantastic combination of offspring they'd produce.

I'm not sure what was the meaning of the ZZ Top song "Velcro Fly," but that was one case where it would have been practical and responsible. (I'm guessing that Velcro Fly refers to rapid deployment groupie management practices. Pearl necklace is yet another similar symbol?)

While you may have met someone similar in your 20+ years of programming experiences, you may not have considered writing your articles for that person who may be reading it. His native language is not English and his experiences are not likely "familiar" when compared to yours. However, if you are able to communicate effectively with him, perhaps his coding style will improve?

Of course, my Chinese friend's coding style did not improve, at least, not by any amount that I could notice. So, perhaps none of my recommendations will have a measurable impact, either!


HTH


MxB
 
 

Recent GIDBlogNot selected for officer school by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 07:44
After execution - Error cannot locate /Skin File? WSCH C++ Forum 1 05-Mar-2005 20:03
CD burner wont burn!! robertli55 Computer Hardware Forum 1 18-Jun-2004 10:53
Yet another CD burner problem: Lite-On LSC-24082K Erwin Computer Hardware Forum 1 22-May-2004 11:28
CD Buring Failed skanth2000 Computer Hardware Forum 1 15-Nov-2003 03:52

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:04.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.