Thread: c script help to read a file & update

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

    Unhappy c script help to read a file & update

    Hi all

    New to c programming , please feel to modofy my code below...this is what i want to do,
    1. i want to read a file and update this file once the user has input the number..
    2. i want to show the contents of the file with the user input entered..

    required output..

    1,2,3,4,5,6,7,8,9,10 - u have entered no. 3

    below 2 code snippets can read a file and accept input from user but i can not list the whole file contents...

    Code:
    #include <stdio.h>
    #define MAX 20
    char string[20];
    
    int main()
    {
        FILE *f;
        int x;
    
    
        f=fopen("file.txt","r");
        if (!f)
    {   printf("Couldn't open file....try again !! txt\n");
            return 1;
    }
        while(fgets(string, 20, f))
    {
        printf("%s", string);
    }
    
            fclose(f);
            return 0;
    }
    above code lists the whole contents of the file....(a.out), how can i modify it so that i can prompt the user to input the number and then print the whole file...can this be done...how...thanks in advance....indy

  2. #2
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164

    Re: c script help to read a file & update

    Originally posted by indy
    Hi all

    New to c programming , please feel to modofy my code below...this is what i want to do,
    1. i want to read a file and update this file once the user has input the number..
    2. i want to show the contents of the file with the user input entered..

    required output..

    1,2,3,4,5,6,7,8,9,10 - u have entered no. 3

    below 2 code snippets can read a file and accept input from user but i can not list the whole file contents...

    Code:
    #include <stdio.h>
    #define MAX 20
    char string[20];
    
    int main()
    {
        FILE *f;
        int x;
    
    
        f=fopen("file.txt","r");
        if (!f)
    {   printf("Couldn't open file....try again !! txt\n");
            return 1;
    }
        while(fgets(string, 20, f))
    {
        printf("%s", string);
    }
    
            fclose(f);
            return 0;
    }
    above code lists the whole contents of the file....(a.out), how can i modify it so that i can prompt the user to input the number and then print the whole file...can this be done...how...thanks in advance....indy
    OK, code is modified to show a much better format for readability

    Code:
    #include <stdio.h>
    #define MAX 20
    char string[20];
    
    int main()
    {
        FILE *f;
        int x;
    
    
        f=fopen("file.txt","r");
        if (!f)
        {   printf("Couldn't open file....try again !! txt\n");
            return 1;
        }
        while(fgets(string, 20, f))
        {
            printf("%s", string);
        }
    
        fclose(f);
        return 0;
    }
    Indent everything within braces to the same level. Braces should indent to the current code level
    As to the rest of the question, I see the following potential steps, not necessarily in order:
    1) read the contents of the file into memoty
    2) display the contents of the file
    3) ask for user input
    4) change the memory contents of the file
    5) write the memory back into the file changing the file itself

    Decide which of these 5 steps you need (and any I may have missed) and the order you need to perform them (maybe even using the same step twice).

    Then look at the code you wrote and decide which of the steps you've done.

    Now what steps need to be added? Where?
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

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

    Unhappy ~ thanks - more help please !!~

    Hi there

    thanks for the help...my inital code just lists the contents of the file, i want to read in to memory and ask the user to enter input number and then print the contents of the file...
    below is the code that prompts the user for input but how can i merge this code with my inital code....thanks in advance...

    [code]

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

    int validate ( char *a )
    {
    unsigned x;
    for ( x = 0; x < strlen ( a ); x++ )
    if ( !isdigit ( a[x] ) ) return 1;
    return 0;
    }

    int main ( void )
    {
    int i;
    char buffer[BUFSIZ];
    printf ( "Enter a number for processing: " );
    if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
    buffer[strlen ( buffer ) - 1] = '\0';
    if ( validate ( buffer ) == 0 ) {
    i = atoi ( buffer );
    printf ( "%d\n", i );
    }
    else
    printf ( "Error: Input validation, please try again...\n" );
    }
    else
    printf ( "Error reading input...try again..!!\n" );
    return 0;
    }

    thanks...indy

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    If you're reading a list of integers separated by commas, it would be easier to treat them as separate entities than as a string. This way you can more easily work with them. Here is an ugly way to do that, you may modify it to suit your own needs:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      FILE *io;
      int  file[BUFSIZ];
      int  i, j;
      int  new_item;
    
      io = fopen ( "input.txt", "r" );
      if ( io == NULL ) {
        perror ( "File open failure" );
        return EXIT_FAILURE;
      }
      i = 0;
      while ( fscanf ( io, "%d%*c", &file[i] ) == 1 )
        i++;
      fclose ( io );
      printf ( "Enter a new item: " );
      fflush ( stdout );
      if ( scanf ( " %d", &new_item ) != 1 ) {
        fprintf ( stderr, "Invalid input" );
        return EXIT_FAILURE;
      }
      io = fopen ( "input.txt", "w" );
      if ( io == NULL ) {
        perror ( "File open failure" );
        return EXIT_FAILURE;
      }
      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;
    }
    My best code is written with the delete key.

  5. #5
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Oops, you didn't use the preview button, did you?

    Simply copy the code snippets that do the task and paste them into the proper place in the other code (or vice versa). Before or after the current code, or between the IF and WHILE -- wherever is appropriate.

    Be sure to order the statements I gave you and understand your code enough to know whice code goes with which statement.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

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

    ~ thanks prelude but more prob !!~

    Hi prelude...

    thanks for the script modification, mych appreciated but i found the following wrong things....

    1. it does not write to the file.txt but writes okay the contents of it...

    2.heres the output i get...from your modified script...
    Enter a new item: 2
    1,2,3,5,7,9,11,13,15,17,19,< machine prompt here !!>
    how can i bring the machine prompt to the new line...

    3.is it possible to echone or print out the value that the user input ??? if so how !!...

    4. what happens if the number entered by the user already exists any chance a message can be displayed...!!...

    waiting for reply...thanks in advance....indy

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

    ~ Sorry prelude...it does work..but !!~

    Hi prelude

    sorry my mistake, it does write to the file, but it does not do the following

    1. i want to limit the max input value to 20 and i did put the following...#define MAX 20 at the top of the program...

    but when i re-run the script and put e.g. say 21 into the input number dialogue it still adds it to the file...how can prevent this , i want to display a message if it is >20, left blank or if the user enters nothing or presses carriage return...in case..
    thanks in advance...indy

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >3.is it possible to echone or print out the value that the user input ??? if so how !!...
    Yes. Just print it out as you normally would:
    Code:
      printf ( "Enter a new item: " );
      fflush ( stdout );
      if ( scanf ( " %d", &new_item ) != 1 ) {
        fprintf ( stderr, "Invalid input" );
        return EXIT_FAILURE;
      }
      printf ( "You entered: %d\n", new_item);
    >4. what happens if the number entered by the user already exists any chance a message can be displayed...!!...
    The code I posted places a duplicate value after the values already present. You can ignore duplicate values completely if you like simply by not writing them to the file.

    >1. i want to limit the max input value to 20 and i did put the following...#define MAX 20 at the top of the program...
    You must ensure that you only read 20 values or less. If you read 20 then you cannot add anymore, otherwise you can. For example:
    Code:
      i = 0;
      while ( i < MAX && fscanf ( io, "%d%*c", &file[i] ) == 1 )
        i++;
      if ( i == MAX ) {
        printf ( "No more items allowed\n" );
        return EXIT_SUCCESS;
      }
    My best code is written with the delete key.

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

    Smile ~ Thanks a lot all !!~

    Hi all

    Thanks again all especially prelude....all the best...going home now...good bye...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM