CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2007
    Posts
    36

    Question reading to unsigned int from text file in c? please help

    Hello there Im trying to simulate machine code and have been given a set of codes

    ::text file contains::
    B404
    239A
    2421
    5345
    350C
    C000

    Im trying to read in each hex number into an unsigned int array, what am i doing wrong?
    Code:
    #include <stdio.h>
    
    
    int main() {
        FILE *f;
        unsigned int instr[80];
        
        f=fopen("a3.txt","r");
        
        while ( fscanf(f,"%x",instr) != EOF){
            int i=0;
            fscanf(f,"%x",&instr[i]);
            i++;
        }
        
        printf("%x %x %x",instr[0],instr[1],instr[2]);
    
        
        
        return 0;
    }
    from there onwards i need to extract 2bytes from one instruction and show output according to a set of Instructions.

    for example:

    1RXY - Load register r with value at memory address XY.

    output would be somthing like this

    PC INSTRUCTION - [R0 R1 R2 R3..etc..]


    All i need to know is how to read each set of instruction into the array. How do i go about doing this?

    -regards



  2. #2
    Join Date
    Aug 2009
    Posts
    10

    Wink Re: reading to unsigned int from text file in c? please help

    a) You should use the c++ functions.....the fscanf, etc, are very prone to programmer error.
    I know you are a beginner, but you would have made fewer errors.

    b) You did not check to see if you opened the file.
    if ( f == NULL) exit(printf("did not open file"));

    c) Your fscanf stated an int, but you gave it a char * buffer.
    d) you did 2 fscanf....

    for ( unsigned int ui; fscanf(f, "%x", &ui )!=NULL; )
    {
    printf("%x", ui);
    }

    e) CLOSE the file.
    if (f)
    fclose(f);

    Hope that helps...I did not compile...just saw a few errors,

    Norman Graham
    c++ programmer for past 20 years.

  3. #3
    Join Date
    Aug 2009
    Posts
    10

    Smile Re: reading to unsigned int from text file in c? please help

    Oh...Opps....you did have a proper array....just not used to seeing old c anymore.

  4. #4
    Join Date
    Oct 2006
    Location
    Singapore
    Posts
    346

    Re: reading to unsigned int from text file in c? please help

    I think you might find this article useful.
    http://www.artima.com/cppsource/streamstrings.html
    Believe in your Dreams, Work for what you Believe in.
    My thoughts? Angelo's Stuff
    Some fun things I've done: RayWatch, QuickFeed, ACSVParser

    @ngelo

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured