File r/w problem

This is a discussion on File r/w problem within the C Programming forums, part of the General Programming Boards category; Hello everyone, I have a little problem with this program. The purpose of the program is to read 2 lines ...

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    9

    File r/w problem

    Hello everyone,

    I have a little problem with this program.
    The purpose of the program is to read 2 lines from a file.
    The first line consist a name and the second line a number.

    For example
    Sergio
    12345

    Then to the second line of the file is added a new value which comes from addition of a new number and the number from the second line of file.
    And this program should be able to use numbers that are max. 300 characters long.
    Now when I run this program "normally" the result is rubbish.
    But when I run this with debugging line by line the add function it works sometimes just fine. And I also noticed that my CPU processor is under heavy "stress" when i debug the code.
    Anyone have an idea what is the reason that this doesnt work?
    Thanks!



    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX 300
    
    void reverse( char * );
    void add( char *, char *, char * );
    void reset( char *, int );
    void empty( char *, int );
    
    int main () {
       FILE * pFile;
       long lSize;
       char * buffer;
    
       pFile = fopen ( "file.txt" , "r+" );
       if (pFile==NULL) {fputs ("File error",stderr);system
    
    ("pause"); exit (1);}
    
       fseek (pFile , 0 , SEEK_END);
       lSize = ftell (pFile);
       rewind (pFile);
    
       buffer = (char*) malloc (sizeof(char)*lSize);
    
       fread (buffer,1,lSize,pFile);
      
       rewind(pFile);
       fflush(pFile);
    
       char * line1;
       char * line2;
       line1 = strtok(buffer,"\n");
       line2  = strtok(NULL,"\n");
       printf("\n%s", line1);
       printf("\n%s", line2);
       
       char number[MAX];
       char result[MAX+1];
       
       reset(number, MAX);
       
       empty(result, MAX+1);
    
       
       printf("\nGive another number: ");
       
       fgets(number,MAX,stdin);
       if(number[strlen(number)-1] == '\n')
          number[strlen(number)-1] = '\0';
       else
          while(getc(stdin) != '\n');
       
       add(line2,number,result);
       printf("\n\n%s",result);
    
       fprintf(pFile, "%s\n", line1);
       fprintf(pFile, "%s\n", result);
       fclose (pFile);
       free (buffer);
      
       fclose(pFile);
       system("pause");
       return 0;
    }
    
    void reverse( char * numb ){
      int lSize = strlen(numb);
      char * copy = (char *)malloc(( lSize + 1) * sizeof(char));
      int i;
    
      for(i=0; i < lSize; i++){
        copy[i] = numb[lSize-1 -i];
      }
      copy[i] = '\n';
    
      for(i=0; i < lSize; i++)
        numb[i] = copy[i];
      free(copy );
    }
    
    void add( char * num1, char * num2, char * num3 ){
    
       int i, j;
       int result = 0;
       int memoryNum = 0;
       int h1, h2;
       int lSize = 0;
    
       reverse(num1);
       reverse(num2);
      
       
       if( strlen(num1) >= strlen(num2))
         lSize = strlen(num1);
       else 
         lSize = strlen(num2);
    
       for(i=0, j=0; i < lSize; i++,j++){
          result = 0;
          
          h1=  (int)(num1[i] - '0');
          if( h1 < 0){
             h1 = 0;
          }
          
          h2 = (int)(num2[j] - '0');
          if( h2 < 0 ){
             h2 = 0;
          }
    
          result = h1 + h2 + memoryNum;
    
          memoryNum = 0;
    
          if( result > 9 ){
     	    memoryNum = result / 10;
    	     result = result % 10;
          }      
          num3[i] = (char)(result + '0');
          
       }// for loop
       
       if( memoryNum > 0)
         num3[i] = (char)(memoryNum + '0');
    
       reverse(num1);
       reverse(num2);
       reverse(num3);
    }
       
    
    void reset( char * number, int lSize ){
    
       int i;
       for(i=0; i < lSize; i++){
         number[i] = '0';
       }
    }
    
    void empty( char * number, int lSize){
       
       int i;
       for(i=0; i < lSize; i++)
         number[i] = '\0';
    
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by scaramanga View Post
    Hello everyone,

    I have a little problem with this program.
    The purpose of the program is to read 2 lines from a file.
    The first line consist a name and the second line a number.

    For example
    Sergio
    12345

    Then to the second line of the file is added a new value which comes from addition of a new number and the number from the second line of file.
    And this program should be able to use numbers that are max. 300 characters long.
    Now when I run this program "normally" the result is rubbish.
    First... lets get clear on the requirements...

    When you say "addition of a new number and the number from the second line" are you talking about mathematical addition or string addition (add to end).

    Moreover when you say 300 character numbers... do you mean real numbers that can be operated upon mathematically or do you mean strings that just happen to hold numeric characters?

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by CommonTater View Post
    First... lets get clear on the requirements...

    When you say "addition of a new number and the number from the second line" are you talking about mathematical addition or string addition (add to end).
    Yes, mathematical addition

    Quote Originally Posted by CommonTater View Post
    Moreover when you say 300 character numbers... do you mean real numbers that can be operated upon mathematically or do you mean strings that just happen to hold numeric characters?
    Yes, real numbers that can be operated mathematically. Only the second line of the file should hold this and the new number that is added can also be 300 digits long

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok, you're not going to do this kind of math with standard C libraries where you are limited by the sizes of the built in variables...

    FWIW the normal range of an int64_t is...
    plus and minus ... 9,223,372,036,854,775,807
    Which is a long way short of 300 digits.

    You will need to use one of the "Big Number" libraries that are available and even they may be hard pressed to go beyond 128 digits.

    Google is your friend....
    Last edited by CommonTater; 03-21-2011 at 08:47 AM.

  5. #5
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    The idea is to store "the number" into array which can hold 300 digits and it is possible to do with the standard libraries. The mathematical addition is done in reverse, cause it is done much easier that way.
    I can get it to work without the file reading and writing but when I add the file reading and writing it prints rubbish. Think the problem might be reading the second line from the file or something else?

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by scaramanga View Post
    The idea is to store "the number" into array which can hold 300 digits and it is possible to do with the standard libraries. The mathematical addition is done in reverse, cause it is done much easier that way.
    Well... good luck with that.

  7. #7
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    In your reverse() function and other places you rely on the length of the string being obtainable because there is a trailing '\0' in them. However, you kill that trailing '\0' by substituting '\n'. That would make future strlen() give unpredictable results.
    Last edited by nonoob; 03-21-2011 at 09:55 AM.

  8. #8
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by nonoob View Post
    In your reverse() function and other places you rely on the length of the string being obtainable because there is a trailing '\0' in them. However, you kill that trailing '\0' by substituting '\n'. That would make future strlen() give unpredictable results.
    Hmmm... How should I use the strlen() then without killing the '\0'? for example, in the add function. Very mysterious to me altough when debugging the code it shows correct values in the add function...

    Quote Originally Posted by CommonTater View Post
    Well... good luck with that.
    I am not sure if you got what I was meaning about the "BigNumbers". Well this is a link to a page that does the same thing a little differently, but the idea is the same. [Courses] A little tutorial about big numbers

    Sorry if I gave you wrong "directions"
    Last edited by scaramanga; 03-21-2011 at 10:36 AM.

  9. #9
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    Code:
     copy[i] = '\n';  /* get rid of this since it kills the necessary terminator */
    
      for(i=0; i < lSize; i++)   /* instead of all this, how about strcpy(numb, copy); */
        numb[i] = copy[i];
      free(copy );
    }

  10. #10
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by nonoob View Post
    Code:
     copy[i] = '\n';  /* get rid of this since it kills the necessary terminator */
    
      for(i=0; i < lSize; i++)   /* instead of all this, how about strcpy(numb, copy); */
        numb[i] = copy[i];
      free(copy );
    }
    Ok, did what u suggested for the reverse function. Now, the output seems like this

    Sergio
    11111
    Give another number: 123456789
    Number1: 11111
    Number2: 987654321HOST_CH╠


    29309912763467900ATH=\Do╚Press any key to continue . . .

    It reads ok the first two lines from the file and then when I input the second number it seems to add some characters to the end.....

    Code:
    void reverse( char * numb ){
      int lSize = strlen(numb);
      char * copy = (char *)malloc(( lSize + 1) * sizeof(char));
      int i;
    
      for(i=0; i < lSize; i++){
        copy[i] = numb[lSize-1 -i];
      }
    
      strcpy(numb,copy);
      free(copy );
    }
    Last edited by scaramanga; 03-21-2011 at 02:39 PM.

  11. #11
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,831
    You should have copy[i] = '\0' after the for loop and before copying to numb.

  12. #12
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Oops, I forgot that from there.
    But still the codes produces weird results.

    The intresting thing is that when I do a program where two numbers are asked from the user it works fine, but when I add the file operations it produces weird stuff.

  13. #13
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Hmmm.....How can I embed to this program so that I can read a variable from a second line of text file to variable N?

    [Courses] A little tutorial about big numbers

    If in the main I write like this, and the BigNumber is defined like this how to write the code for reading from the file?


    #define MAX 300

    typedef int BigNumber[MAX];
    BigNumber N, C, S;

    ****
    code
    ****

    FILE * pFile;

    pFile = fopen ("file.txt","r");
    rewind (pFile);
    char name[5];
    fscanf (pFile, "%s", name);

    *how to read the second line to variable N

    printf("\%s",N);
    fflush(pFile);

    int i;

    printf("Input a big number (B): ");
    readbignumber(C);
    AddBigNumbers(N,C,S);
    printf("\nA+B = ");
    printbignumber(S);
    SubBigNumbers(N,C,S);
    printf("\nA-B = ");
    printbignumber(S);
    system("pause");
    fclose(pFile);
    return 0;

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You can read an entire line of text into your char buffer, like this:

    fgets(buffer, sizeof(buffer), filePointer);

    Then move each digit to the number array, as an int
    Code:
    char buffer[302]; //2 for \n and '\0' char's
    int number[300];
    i = 0;
    while(buffer[i] != '\n') {
      sprintf(number[i], "%d", buffer[i]);
      ++i;
    }

  15. #15
    Registered User
    Join Date
    Mar 2011
    Posts
    9
    Quote Originally Posted by Adak View Post
    You can read an entire line of text into your char buffer, like this:

    fgets(buffer, sizeof(buffer), filePointer);

    Then move each digit to the number array, as an int
    Code:
    char buffer[302]; //2 for \n and '\0' char's
    int number[300];
    i = 0;
    while(buffer[i] != '\n') {
      sprintf(number[i], "%d", buffer[i]);
      ++i;
    }
    Ok, so you mean i could first read the first line like this
    fscanf(pFile,"%s", name)
    and then read the second line from the file like that to the variable N like this

    #define MAX 300

    typedef int BigNumber[MAX];
    BigNumber N, C, S;

    fgets(buffer, sizeof(buffer), pFile);
    char buffer[302];
    i = 0;
    while(buffer[i] != '\n') {
    sprintf(N[i], "%d", buffer[i]);
    ++i;
    }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Leak in AppWizard-Generated Code
    By jrohde in forum Windows Programming
    Replies: 4
    Last Post: 05-19-2010, 04:24 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. File I/O problem
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 12
    Last Post: 09-03-2005, 12:14 PM
  5. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21