Thread: ~Help - File processing with user input~

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy ~Help - File processing with user input~

    Hi all

    This may sound like a silly/simply question how do i create a file from user input e.g. i want the user to input a file name and that input creates a file with same name...

    required output...

    1.Input file name to process: xyz (this xyz is created)then
    i want to make sure the entry is made, if blank output a message..

    2. which line no. to enter the data into...

    3. Enter text....prompt user to ok to continue if no quit

    4.if yes enter the text into the line no. and display it ...

    i would appreciate if someone can give a c program script to get me started, thanks in advance....i am new to c programming...thanks again...indy

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Here is some code to open a file for writing (creating it if necessary) and add some arbitrary text to it. You can use this to develop your own solution based on your needs.
    Code:
    FILE *out;
    char filename[FILENAME_MAX];
    char text[BUFSIZ];
    
    printf ( "Enter a file to create: " );
    fflush ( stdout );
    if ( fgets ( filename, sizeof filename, stdin ) != NULL ) {
      char *newline = strrchr ( filename, '\n' );
    
      if ( newline != NULL )
        *newline = '\0';
      out = fopen ( filename, "w" );
      if ( out == NULL ) {
        perror ( "File open failure" );
        return EXIT_FAILURE;
      }
      printf ( "Enter text for your new file: " );
      fflush ( stdout );
      if ( fgets ( text, sizeof text, stdin ) != NULL )
        fputs ( text, stream );
      fclose ( out );
    }
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy ~thanks prelude - more help please~

    hi prelude

    thanks for the reply, but this is what i want to do , sorry i did not explain properly...

    i want to enabling a user to insert a line in a specific part of a text file, i.e.
    - ask user the name of the file,
    - ask user where (line number) s/he wants to insert the line
    - ask user to provide the text for this line


    You then insert this line into the specific part of the file and ask user whether s/he wants to continue or not.

    i would appreciate any sort of code snippet/script, i have tommorrow to finish it ...waiting for reply....thanks again...indy

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >ask user the name of the file
    Already answered.

    >ask user where (line number) s/he wants to insert the line
    You can find the answer to this in the FAQ.

    >ask user to provide the text for this line
    Already answered.

    But it strikes me that these three requirements are not your problem. What you really want to know is how to insert a line of text into an indexed file. The answer is that it would be easier to read the entire contents of the file into memory, then insert your new line at the desired location and rewrite the data back to the file:
    Code:
    i = 0
    while not eof
      read a line
      add the line to a linked list
      i = i + 1;
      if i == line_number
        add new line to the linked list
      endif
    loop
    # Reopen the file for writing
    while list not empty
      write a line to the file
      remove a line from the linked list
    loop
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    ~ thanks yes but ~

    hi there prelude

    thanks for the logic, what i was thinking is would it not be better to check if the file exists or prompt the user to read the text file, if y continue then abort...code would appreciated...thanks in advance...indy

    Code:
    i = 0
    while not eof
      read a line
      add the line to a linked list
      i = i + 1;
      if i == line_number
        add new line to the linked list
      endif
    loop
    # Reopen the file for writing
    while list not empty
      write a line to the file
      remove a line from the linked list
    loop

  6. #6
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >would it not be better to check if the file exists or prompt the user to read the text file
    Yes, it would. That way you don't throw away anything in an already existing file. To test if a file exists, simply try to open it for reading. If fopen fails, the file most likely doesn't exist, so you can then go right to the writing step. Otherwise, follow the logic I gave earlier.

    >code would appreciated
    The code is trivial, I'm sure you can handle it.
    My best code is written with the delete key.

  7. #7
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy ~ More help on my code prelude~

    Hi there prelude...

    thanks for the reply, heres my code so far, i want to incoperate my previous logic...i real sloww in getting it into script and i need more help...thanks...indy



    Code:
    #include "stdio.h"
    #include "stdlib.h"
    
    void main(void)
    {
     FILE *fp;
     char fname[128];
    
     printf("Enter filename: ");
     gets(fname);
    
     if((fp=fopen(fname, "r"))==NULL) {
     printf("cannot open file\n");
     exit(1);
    }
    
    fclose(fp);
    }

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's a good start, with a couple of problems:
    1) 'main' always returns an int, not void. Thus, your main function should be:
    Code:
    int main( void )
    {
        ...code...
    
        return 0;
    }
    2) You shouldn't use gets, because it has problems also. Such as, it doesn't check input size, so it's abusable and can cause your program to crash. It doesn't safety check the input size, so it likes to ramble off the end of your array and corrupt your application.

    You should use fgets instead. Consider reading this FAQ entry on how to correctly read a line from a user.

    From there, see what else you can come up with, and we'll point you in the right direction.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy ~ More help !!..code not working~

    Hi ther quaze

    thanks for the reply,hint...much appreciated, i have the code below which i want to modify so that i can prompt the user with the following while reading a file into memory..

    1. enabling a user to insert a line in a specific part of a text file, i.e.
    - prompt user the name of the file,
    - prompt user where (line number) s/he wants to insert the line
    - prompt user to provide the text for this line

    then i want to insert this line into the specific part of the file and ask user whether s/he wants to continue or not.

    the code below works but only prompts the user new number to be added, adds it and lists the contents of the whole file...how can i modify it to ask for the above user inputs...feel free to modify ...thanks in advance...indy

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    /* Define the maximum value e.g. 20 in this case.*/
    
    #define MAX 20
    
    int main ( void )
    
    /* File/Integer declarations.*/
    
    {
      FILE *io;
      int  file[BUFSIZ];
      int  i, j;
      int  new_item;
    
    /* Reading the input file with read mode.*/
    
      io = fopen ( "file.txt", "r" );
    
    /* Open file failure error routines.*/
    
      if ( io == NULL ) {
        perror ( "File open failure" );
        return EXIT_FAILURE;
    }
      i = 0;
      while ( fscanf ( io, "%d%*c", &file[i] ) == 1 )
        i++;
      fclose ( io );
    
    /* User input declaration.*/
    
      printf ( "Enter a new number to be added to the file..: " );
      fflush ( stdout );
    
    /* Output Buffer setup.*/
    
      if ( scanf ( " %d", &new_item ) != 1 ) {
        fprintf ( stderr, "Sorry Invalid input, please try again..!!" );
        return EXIT_FAILURE;
    }
      io = fopen ( "file.txt", "w" );
      if ( io == NULL ) {
        perror ( "File open failure" );
        return EXIT_FAILURE;
    
    /* New entry input & modifications and output to screen.*/
    
    }
      for ( j = 0; j < i && file[j] <= new_item; j++ ) {
        fprintf ( io, "%d,", file[j] );
        printf ( "%d,", file[j] );
    }
      fprintf ( io, "%d,", new_item );
      printf ( "%d,", new_item );
      for ( ; j < i; j++ ) {
        fprintf ( io, "%d,", file[j] );
        printf ( "%d,", file[j] );
    }
      fclose ( io );
    
      return EXIT_SUCCESS;
    }
    thanks again...indy

  10. #10
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Well,
    [i]while ( fscanf ( io, "%d%*c", &file ) == 1 )
    The fscanf() format "%d%*c" requires 3 parameters, you supplied 1. The %d gets placed in the i'th byte in file, the rest are lost.

    Also, all the while loop does is populate the entire file buffer with the integer in the first postition of each line of the file.

    As far as

    1. enabling a user to insert a line in a specific part of a text file, i.e.
    - prompt user the name of the file,
    - prompt user where (line number) s/he wants to insert the line
    - prompt user to provide the text for this line
    Tips:
    do NOT use scanf -- at all! Use fgets for all input (file and user) to prevent unexpected results. Examples are all over this forum -- search them out, check the FAQ

    Reread Prelude's first post -- she gave you most of what you need.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  11. #11
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy thanks - sloww coder...need more help..

    hi there

    thanks walt p ...i bit confused and having problems with adding text for a line number...had a look at the faq/archive but still having problems, my code below, does ask for file name and line number to add text but does not insert the text to that line number, have used cput,cget to add text, where is it i am going wrong...now it does not compile either...sorry...thanks in advance...i am too sloww for this group...sorry

    Code:
    #include "stdio.h"
    #include "stdlib.h"
    
    void main(void)
    {
      FILE *fp;
      char s[80];
      int t;
      char p[23];/* for text for line number.*/
      s[0] = 20;
    
      if ((fp = fopen("test", "w")) == NULL) {
       printf("sorry...cannot open file.. !!\n");
       exit(1);
    }
    
     printf("Enter file name & Line Number to insert data.. : ");
    
    /* Read from keyboard. */
    
     /*fscanf(stdin, "%s%d", s, &t);*/
    
       fscanf(stdin, "%s%d", s, &t, "%p%d", p);
      /* read text for the location.*/
    
      cputs("Enter text for Line number to  insert.. : ");
      cgets(s);
      cputs(&s[2]);
    
    /*write to file.*/
    
       fprintf(fp, "%s %d", s, t);
    
       fclose(fp);
    
       if((fp=fopen("test", "r")) == NULL){
        printf("sorry...cannot open file.. !!\n");
        exit(1);
    
    /* read from a file.*/
    
       fscanf(fp, "%s%d", s, &t);
    
    /* print to screen.*/
    
       fprintf(stdout, "%s %d", s, t, p);
    }
    thanks in advance...indy

  12. #12
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You've clearly butchered the code you've been given thusfar. Why don't you try starting over with the complete program I provided you that does what you want with a file of integers. All you need to do is modify it to use strings instead, and the FAQ tells you how to read and write strings correctly.
    My best code is written with the delete key.

  13. #13
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    ~ sorry - was bit lost !!~

    hi prelude...

    thanks...but i am bit confused and have alot of versions , yes i have well butchered it u are right, could u please start me off again....heres what i want to do...

    enabling a user to insert a line in a specific part of a text file, i.e.
    1-ask user the name of the file,
    2- ask user where (line number) s/he wants to insert the line
    3.ask user to provide the text for this line
    4.then insert this line into the specific part of the file and ask user whether s/he wants to continue or not.



    thanks again...indy

  14. #14
    Registered User
    Join Date
    Dec 2003
    Posts
    21

    Unhappy ~ new code ...from scratch...

    hi prelude

    this is what i have from scartch...

    Code:
    #include <stdio.h>
    
    #define MAX 10
    #define LEN 80
    
    char text[MAX][LEN];
    FILE *openinfile(void);
    
    void main(void)
    {
            register int t,i,j;
            int n,row,p,x;
            char y[80];
            FILE * fp;
            n=0;
    
            fp = openinfile();
            for (row=0;row<10;row++)
            {
                    fgets(text[row],LEN,fp);
            }
            fclose(fp);
    
            for(i=0;i<MAX;i++)
            {
                    for(j=0; text[i][j];j++) putchar(text[i][j]);
            }
    
            printf("Enter text line to edit : \n");
            scanf("%d", &n);
    
            printf("Line selected is : %s\n", text[n]);
    
            printf("Enter text for line....\n");
            gets(text[n]);
            if(!*text[n]) gets(text[n]);
    
     for(i=0;i<MAX;i++)
            {
                    for(j=0; text[i][j];j++) putchar(text[i][j]);
            }
    }
    
    FILE *openinfile(void)
    {
            FILE *fp;
            char infile[25];
    
            printf("Input filename : ");
            gets(infile);
            fp = fopen(infile, "r");
            return fp;
    }

  15. #15
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >could u please start me off again....
    Make sure you understand this completely before making any changes.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    #define MAX 20
    
    int main ( void )
    {
      char file[MAX][BUFSIZ];
      char new_item[BUFSIZ];
      FILE *io;
      int  pos;
      int  i;
      int  j;
    
      for ( ; ; ) {
        io = fopen ( "input.txt", "r" );
        if ( io == NULL ) {
          perror ( "File open failure" );
          return EXIT_FAILURE;
        }
        for ( i = 0; fgets ( file[i], MAX, io ) != NULL; i++ )
          ;
        fclose ( io );
        printf ( "Enter new text to be added to the file..: " );
        fflush ( stdout );
        if ( fgets ( new_item, sizeof new_item, stdin ) == NULL ) {
          fprintf ( stderr, "Invalid input" );
          return EXIT_FAILURE;
        }
        printf ( "Enter the location to insert the new text: " );
        fflush ( stdout );
        if ( scanf ( " %d", &pos ) != 1 ) {
          fprintf ( stderr, "Invalid input" );
          return EXIT_FAILURE;
        }
        if ( pos < 0 )
          pos = 0;
        if ( pos > i )
          pos = i;
        io = fopen ( "input.txt", "w" );
        if ( io == NULL ) {
          perror ( "File open failure" );
          return EXIT_FAILURE;
        }
        for ( j = 0; j < pos; j++ ) {
          fprintf ( io, "%s", file[j] );
          printf ( "%s", file[j] );
        }
        fprintf ( io, "%s", new_item );
        printf ( "%s", new_item );
        for ( ; j < i; j++ ) {
          fprintf ( io, "%s", file[j] );
          printf ( "%s", file[j] );
        }
        fclose ( io );
        printf ( "Add another line? (y/n): " );
        if ( tolower ( getchar() ) != 'y' )
          break;
        while ( getchar() != '\n' )
          ;
      }
    
      return EXIT_SUCCESS;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Totally confused on assigment using linked lists
    By Uchihanokonoha in forum C++ Programming
    Replies: 8
    Last Post: 01-05-2008, 04:49 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM