Thread: How can I write an input string to a text file? Please help.

  1. #1
    Registered User MarkSquall's Avatar
    Join Date
    Aug 2007
    Posts
    27

    Cool How can I write an input string to a text file? Please help.

    Dear Cprogramming.com members and administrator,

    Good day to everyone. I programmed this simple C program that accepts an string input and display it on the screen:

    Code:
    #include<stdio.h>
    #include<string.h>
    int main()
    {
     char name[20];
     printf("Please enter your input string: ");
     gets(name);
     printf("Hello.  Your input is: %s", name);
     getch();
     return 0;
    }
    It works fine, but I just have certain questions on this like:

    1. What necessary C code will I add on this so that my input will be saved on a textfile? Let's
    say when I input a string, the string (or maybe the message plus the name) will be
    saved to a file named"hello.txt" (I just wonder about this thing because in Java, I have
    this is possible using the BufferedWriter class to put my string in a textfile).

    2. Can I use a "maximum" length in array without defining it? I mean what if I want more than
    20 characters, 40 characters, 60, etc? Or there's no other way but to "maximize"
    beforehand the array length of the said array declaration?



    Thank you and more power to everyone.


    Respectfully yours,

    MarkSsquall

  2. #2
    Registered User
    Join Date
    Jan 2008
    Posts
    18
    Quote Originally Posted by MarkSquall View Post
    Dear Cprogramming.com members and administrator,



    It works fine, but I just have certain questions on this like:

    1. What necessary C code will I add on this so that my input will be saved on a textfile? Let's
    say when I input a string, the string (or maybe the message plus the name) will be
    saved to a file named"hello.txt" (I just wonder about this thing because in Java, I have
    this is possible using the BufferedWriter class to put my string in a textfile).
    MarkSsquall
    You simply open file "hello.txt" and use fprintf() to write this string into it.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Sounds like you could use a C FAQ or tutorial! This board has one, and I'll add another one for you, in a bit.

    Basically, you make a file ptr, and tell the program what the name of the file is, and how you would like to have that file open (read, write, binary, text, or even read & write combinations).

    You can declare an array size in advance, or you can declare it dynamically as you need it. You can reallocate it's size, etc. Some compilers allow a little "fudge" trick for this, as well. (Don't know if it's standard or not, though, or how many will allow it.)

    This is a nice tutorial for C: http://www.cs.cf.ac.uk/Dave/C/

    You can skip the unix stuff, of course.
    Last edited by Adak; 01-14-2008 at 02:43 AM.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You should also avoid gets - you should use fgets instead!
    And one space for indentation? That's a little cheap, don't you think? Usually, 4 spaces or a tab is recommended.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User MarkSquall's Avatar
    Join Date
    Aug 2007
    Posts
    27

    Thumbs up The code was successfully working, how would I read the file then? Please help.

    Dear Adak, invinciblevn,

    Good day everyone. Thank you for the website you've shared Adak, I try to work on this out based on the website you gave, and I have come up with the code, here it is (please feel free to suggest/correct me more if I "lack" or "violate" something):
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    int main()
    {
        char name[20];
        char choice;
        FILE *stream, *fopen();
        clrscr();
        stream = fopen("sample.txt","w");
        if ( (stream = fopen("sample.txt","w") ) == NULL)
        {
              printf("Sorry, cannot open the file %s","sample.txt");
              exit(1);
        }
        else
       {
             printf("Please enter your name: "); 
             gets(name);
             if ( (stream = fopen("sample.txt","w") ) != NULL)
                 fprintf(stream, "%s", name);
        }
        getch();
        return 0;
    
    } /*end of main */
    Thanks again for the site and info Adak, invinciblevn. But I want to add more to this simple program, that is, after writing the string to my sample.txt, I want my program to read it now, I want to put this line of code before the getch() function:

    Code:
       printf("Do you want to open and read your file?[Y/N]: ");
       scanf("%c", &choice);
       if( (choice=='Y') || (choice=='y') )
              /*  what C code will I put here? */
       else if ( (choice=='N') || (choice=='n') )
             printf("Thank you...");
       else
             printf("Invalid input, please try again.");
    From the code above, what C code will I add so that if I press Y or y, my program will read the file sample.txt.

    And one more thing, the program automatically creates SAMPLE.TXT (all caps), but while in the source code, the filename is all lowercase? Do I have a workaround on this? I mean, can I make it all lowercase or it depends on my compiler? I'm using Turbo C by Borland (running in DOS).

    Thank you and God bless everyone.


    Respectfully yours,

    MarkSquall

  6. #6
    Registered User
    Join Date
    Jan 2008
    Posts
    18
    From you code, I see some problem:
    + You open a file but do not close this file.
    +
    stream = fopen("sample.txt","w");
    if ( (stream = fopen("sample.txt","w") ) == NULL)
    Open a file when it's already opened.

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MarkSquall
    And one more thing, the program automatically creates SAMPLE.TXT (all caps), but while in the source code, the filename is all lowercase? Do I have a workaround on this? I mean, can I make it all lowercase or it depends on my compiler? I'm using Turbo C by Borland (running in DOS).
    Welcome to Microsoft operating systems, where "case sensitivity" is just a random string of 16 characters. Although: if you chosen a compiler made within the last, oh, fifteen years or so, it would have created a file with a lower-case name as specified. Say it with me: Visual C++ Express, Dev-C++, Code::Blocks. All free, IDE-driven, Windows-compatible compiler suites.

    As to your actual question, you need it all, basically. All your first code did was open a file, read a string, and write to the file, which is what you want to have happen when they type 'Y'. But note, only use fopen once! Once a file is open, it will stay open until you fclose it.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I have a few suggestions for you.
    Close the file after opening it. Open the file once. Don't use gets! Get on with the times, use a proper OS. Scrap that POC compiler and get a real IDE.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by MarkSquall View Post
    Code:
    FILE *stream, *fopen(); /*wrong */
    fopen is already declared in stdio.h, and that's not how you declare a function prototype. Just delete the red.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by robwhit View Post
    fopen is already declared in stdio.h, and that's not how you declare a function prototype. Just delete the red.
    Well, it's a legal prototype declaration, but it's a really bad idea, because no parameter information is supplied.

    Why not to use gets(): cpwiki.sf.net/index.php/gets
    Also see Elysia's signature.

    I also suggest reading a file tutorial. If Adak's didn't help, perhaps this one will: http://www.cprogramming.com/tutorial/c/lesson10.html

    Or have a look at this sample (codeformed) program.
    Code:
    #include <stdio.h>
    
    int main(void) {
        FILE *fp;
        fp = fopen("file.txt", "a");  /* open "file.txt" for append mode */
    
        if(fp == NULL) {
            fprintf(stderr, "Cannot open \"file.txt\" for appending\n");
            return 1;  /* exit with an error code */
        }
    
        fputs("Hello, World!\n", fp);  /* write some data to the file */
    
        fclose(fp);  /* close the file */
    }
    Append mode is quite useful. It allows you to write to the end of the file without emptying the file first (which is what write mode, "w", does).
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by dwks View Post
    Well, it's a legal prototype declaration, but it's a really bad idea, because no parameter information is supplied.
    Additionally, any parameter information you supply would make it incompatible with either C89 or C99, as they have different signatures.
    Last edited by robwhit; 01-15-2008 at 06:38 PM.

  12. #12
    Registered User MarkSquall's Avatar
    Join Date
    Aug 2007
    Posts
    27

    Talking Thanks for all the replies.

    Dear Cprogramming.com members,


    First I want to thank for those who make time correcting my code and gave proper coding in my sample C program, I really do appreciate it, I'll remember such suggestions, thanks again. I have downloaded Dev-C++ and Code::Blocks and it is really a nice environment, I'll be familiarizing them as of now, but anymore IDE you can suggest? I have Microsoft Visual C++ but I'm always encountering a problem when I tried to compile them, eventhough I just followed what the books have written, that's why I'd uninstalled it and kept just Visual Basic, I'll just post what kind of problem is that.


    Adding to dwks code, what if the program (as I want to add) ask if the user wants to read that file, and if I type Y/(or y) for YES, what code will I add? If I enter: Cprogramming.com and it will save to a file (it works) and if the program ask "Do you want to read the file?" if I enter Y, it will just display Cprogrammming.com in the output.


    God bless everyone.




    Repectfully yours,

    MarkSquall

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by MarkSquall View Post
    Dear Cprogramming.com members,

    Adding to dwks code, what if the program (as I want to add) ask if the user wants to read that file, and if I type Y/(or y) for YES, what code will I add? If I enter: Cprogramming.com and it will save to a file (it works) and if the program ask "Do you want to read the file?" if I enter Y, it will just display Cprogrammming.com in the output.
    You need to reopen the file in read mode, and read it in and display it. You should use fgets() to read from the file.

  14. #14
    Registered User MarkSquall's Avatar
    Join Date
    Aug 2007
    Posts
    27

    Talking

    Dear tabstop,

    Thanks for the information you gave, I guess that concludes my problem now.


    Open the file ---> ask input ---> write the input to the file ---> close the file ---> reopen again ---> the read the content of the file --->close again the file...I guess that makes the "real" workaround in my program. Thank you Sir/ everyone!


    God bless everyone.


    Repectfully yours,

    MarkSquall

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    It should be noted that you can open a file for, say, "a+" mode, which allows you to append to a file, rewind() it (or whatever), and then read from it. "w+" would work as well.

    For more information, check out one of these.
    http://www.cplusplus.com/reference/c...dio/fopen.html
    http://www.cppreference.com/stdio/fopen.html
    http://www.opengroup.org/onlinepubs/...xsh/fopen.html
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM