954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

turning userinput into a text file

how to turn a user input into a text file for example user inputs 100 and the program creates a text file named 100.txt?
I have tried to work it out but it still doesnt work properly.
i used

getc(stdin);  

char filename[80];
sprintf(filename,"%d.txt", stdin);


and then i also tried

char line[255];
fgets(line, 255, stdin);
   
char filename[80];
sprintf(filename,"%d.txt", stdin);

any ideas on why it wont create the text file?

cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

This line is incorrect:

sprintf(filename,"%d.txt", stdin);



Since you've already gotten the input from stdin, you should be supplying the variable which contains the user input as an argument instead of stdin .

And since you read it in as a string, you'll want to change "%d" to "%s". Also beware of newlines in your string, which could thoroughly mess up your program.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

the program runs, but no output file is generated? am i missing a command still?

char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);
cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

Read my last sentance:
Also beware of newlines in your string, which could thoroughly mess up your program.

You're going to have to remove the newline character (if it's there), which is usually as simple as doing the following

if (string[strlen(string)-1] == '\n')
   string[strlen(string)-1] = '\0';


Anyhow, the code works fine for me, even without the newline character removal. So perhaps it would be best for you to show us the code you're using?

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

well the entirety is only

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);
  return 0;
}
cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

the program runs, but no output file is generated? am i missing a command still?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
char line[255];
fgets(line, 255, stdin);
char filename[80];      // This line can't be here.  It has to 
                        // be above all executable code in C
sprintf(filename,"%s.txt",line);
  return 0;
}


Yeah. Where do you:
1) open the file after you generate the name?
2) write to the file?
3) close the file before exiting?
:?:

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

well all i want to do is for the user to input a name or number and for the program to create a text file with that name. im not actually writing anything into the file, its just an empty .txt file with a name that hte user chose

cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

You still have to open the file for writing. It doesn't magically get created just because you create a name in a variable...

Look up fopen()

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

well i used

fout = fopen("%s.txt", "w");

but how do i represet "%s.txt" as the user's input?

cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

well i used

fout = fopen("%s.txt", "w");

but how do i represet "%s.txt" as the user's input?

you already posted the answer to that question in your post #5. Just use variable filename

sprintf(filename,"%s.txt",line); // <<< from your previous post
fout = fopen(filename, "w");
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

but i though the entry in fopen has to be a either in "" or predefined?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define INFILE "questions.txt"


int main(int argc, char *argv[]) {
        char mc;
        char rt;
        char filename[80];
        char line[255];
 FILE *fin,*fout,*fid;
fin = fopen(INFILE, "r");  


printf("enter student ID:");   
fgets(line, 255, stdin);
sprintf(filename,"%s.txt",line);

fout = fopen(filename, "w");
return 0;
}
cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 
but i though the entry in fopen has to be a either in "" or predefined?

It can be, but it can also be a variable, such as I posted. All it is looking for isconst char*, doesn't care if it is a char variable or a literal string.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

but when i leave it as (filename,'w') and compile and run, the program notes a windows error and closes, and no file is generated

cusado
Light Poster
27 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
 

fgets() function leaves the '\n' in the input buffer, so you need to truncate it

printf("enter student ID:");
fgets(line, 255, stdin);
// truncate '\n'
if( line[strlen(line)-1] == '\n')
   line[strlen(line)-1] = '\0';
sprintf(filename,"%s.txt",line);
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
but i though the entry in fopen has to be a either in "" or predefined?


Why would you think that? ;)well i used

fout = fopen("%s.txt", "w");
but when i leave it as (filename,'w') and compile and run, the program notes a windows error and closes, and no file is generated


Why did you change"w" to 'w'? Change it back and it will work.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

the program runs, but no output file is generated? am i missing a command still?

char line[255];
fgets(line, 255, stdin);
char filename[80];
sprintf(filename,"%s.txt",line);



Here is a program to solve your problems. Make sure you're include files are being properly included.

#include <stdio.h>
#include <string.h>
#define MAXINPUT 100

/* Function used if the user didn't pass program parameter */
void getUserInput(void);
 
/* udtf (user defined text filename) is the global character variable buffer.                                                                                   */
char udtf[MAXINPUT];
 
/* Create a constant character array holding the file extentions - you can change the saved file type simply by changing this initialization                                                                               */
const char fext[] = "txt";
 
/* See below for information regarding the keywords "static" and "inline". This is just a header printed for standard information to the user about the program, including how view usage information
or they'll probably never know how.                                                               */
static inline void _header(void)
{
    puts("UDTF (User Define Text Filename) version 1.0");
    printf("Passed parameters or a prompt will allow a user to create a text file whose \nfilename is specifed by the user using the sprintf function");
    printf("For usage \ninformation pass the -h parameter to the program.\n\n");
}
 
/* This is a static funciton which simply means that only the scope of this program is able to access it. Inline means that the function is expanded where it is called; Note that it is not good practice to use inline functions that contain a massive block of code. This function is for usage information at the users request.                                                       */
static inline void _usage(const char *prog_name)
{
    printf("%s -h Show usage help information\n", prog_name);
    printf("%s filename", prog_name);
}
 
int main(int argc, char *argv[])
{
    /* For the noobs sake, the FILE pointer fp will hold a handle or the address returned after issuing the fopen(...) function and will be used for referrence to the open file - which in this case will just close because you simply specified the user create a text file.      */
    FILE *fp;
 
    /* Show program header - refer above for an explaination */
    _header(); 
 
    /* Check to see if the user passed any program parameters so we can use it instead of prompting  the user for a name. Essentially, the argc variable holds the number of parameters passed to the program including the program name itself, which is why its argc > 1 rather than argc > 0.    */
    if (argc > 1)
    {

        /* Check if the user requests usage information */
        if (!strcmp(argv[1], "-h"))
        {

            /* The program name is pointed to by argv[0] - the first element of the array */
            _usage(argv[0]);
            goto End;
        }
 
        /* So if the user passed a program paremeter which'll represent the name of the text file so we don't have to prompt the user, we first make sure the string length of the first parameter char array pointed to by argv[1] doesn't exceed the MAXINPUT constant defined above.
You can change the max input simply by changing the value assigned to the MAXINPUT constant (i.e #define MAXINPUT 80)                                                                   */

        if (strlen(argv[1]) > MAXINPUT) {
   
            /* If the string legnth exceeds MAXINPUT prompt the user */
            getUserInput();
        }
        else
 
            /* Copy the string pointed to by argv[1] into the udtf buffer */
            strcpy(udtf, argv[1]);
    }
    else
        /* If no parameters were passed prompt the user */
        getUserInput();
 
   sprintf(udtf, "%s.%s", udtf, fext);
   /* Attempt to open file use the filename now stored in the udtf buffer and show error if unsuccessful.                                                                         */
    if ((fp = fopen(udtf, "r+")) == NULL) {
        printf("Error: unable to open file %s", udtf);
        return 1;
    }
 
    fclose(fp); /* Close the file */
 
    /* You really shouldn't use goto's they're gay but what-the-hell */
    End:
 return 0;
}
 
/* This function will be used to prompt the user and get the file name via stdin */
void getUserInput(void)
{
    char cinc;
    int a = 0;
    
    printf("Filename: ");
 
    /* While loop getting character by character off stdin using the increment counter a into the global udtf buffer. If you're not aware of what a global variable is, it is a variable that is accessible to all code within the scope of that program. If when the enter key is pressed
or a == MAXINPUT then we want to break the loop and move on.                              */
    while ((cinc = getc(stdin)) != '\n')
    {
        if (a == MAXINPUT)
            break;
        udtf[a] = cinc;
        a++;
    }

    /* Before we return add a end-of-string character so we don't print out garabage. */
    udtf[a]= '\0';
}
Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 
/* You really shouldn't use goto's they're gay but what-the-hell */
    End:


"Practice what you preach."
If you
1) know you shouldn't use them,
2) then say you shouldn't use them,
3) and do it anyway,
what are you teaching the people that are new to the language? It's confusing because for them, the code is now useless. They don't understand enough to know what to ignore and what is good... FYI... ;)

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
"Practice what you preach." what are you teaching the people that are new to the language? It's confusing because for them, the code is now useless. They don't understand enough to know what to ignore and what is good... FYI... ;)



I think you should speak for yourself buddy. The code isn't useless BECAUSE of the comments. The reason why I used a goto statement is because it is very intuitive and thus would be easier for a begginer to understand. However, I just wanted to imply that using the goto statement is usually not good depending on the application and/or specifications of a software project - which they're not quite up to, yet, but it is good to keep this in mind becuase instructors discourage its use. I do understand what you say by it might be confusing but even a newbie will know how to distinguish comments from actual code, so, therefore, it is less confusing and more informative - which is what comments are for, right. Last, when you wrote, and I quote, "the code is now useless", well, that just your opinion; one opinion. An absolute newbie, if truely curious, could just google the keyword goto and it'll give a brief, easy-to-understand description of it. So I suppose you're a newbie?!?!

LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

Also, not to be rude, but the code posting was kind of pointless.The code was MAJORLY overcommented.
The fix the OP needed was just a matter of one or 2 lines.
There was nothing the OP needed to know in your post that hadn't already been shown already.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

Oh if you're a newbie and are looking for a very intuitive C/C++ IDE I recommend Code::Blocks if you were not aware. It is absolutely free for download. Here is the link for the download:

http://www.codeblocks.org/downloads.shtml

You'll see a seciton labeled "Code::Blocks IDE (Windows Binaries)", and if you're using Windows, you'll click the "Code::Blocks IDE with MINGW Compiler" if you need too. Good luck my fellow Daniweb friends

LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You