topcat
topcat

Reputation: 189

How to implement searching words in a file and then writing in another file?

Im trying to make SIC assembler in c, made a small test program to search for "START" keyword and get the starting address from the assembly code file. then write them in another file as first pass. code didn't work. mind telling whats wrong with it?

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

int main(int argc, char *argv[])
{
    FILE *source;
    FILE *intermediate;
    rewind(source);
    char word[10];
    unsigned int address = 0;
    char start[5] = "START";
    source = fopen(argv[1],"r");
    intermediate = fopen(argv[2],"r+");
    while(strcmp(word,start) != 0)
    {
        fscanf(source, "%s", word);
    }
    fscanf(source, "%x", address);
    fprintf(intermediate, "%x", address);
    fprintf(intermediate, "%s", word);

    return(0);
}

this is the assembly input:

  COPY   START  1000
  FIRST  STL    RETADR
  CLOOP  JSUB   RDREC
         LDA    LENGTH
         COMP   ZERO
         JEQ    ENDFIL
         JSUB   WRREC
         J      CLOOP
  ENDFIL LDA    EOF
         STA    BUFFER
         LDA    THREE
         STA    LENGTH
         JSUB   WRREC
         LDL    RETADR
         RSUB
  EOF    BYTE   C'EOF'
  THREE  WORD   3
  ZERO   WORD   0
  RETADR RESW   1
  LENGTH RESW   1
  BUFFER RESB   4096

Upvotes: 0

Views: 55

Answers (1)

4386427
4386427

Reputation: 44329

As I and others pointed out in comments, you have several errors.

1) Use of uninitialized variables (word)

2) rewind on file not open

3) Too short arrays for a string (start)

4) Wrong arguments to fscanf (address instead of &address)

Besides that there are other problems like:

1) Risk of buffer overflow in fscanf

2) Missing handling of EOF

3) Missing close of files

After fixing the above, the code could look like:

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

int main(int argc, char *argv[])
{
    FILE *source;
    FILE *intermediate;
    char word[10];
    unsigned int address = 0;
    const char start[] = "START";

    source = fopen(argv[1],"r");       // Missing check of argc and successful file open
    intermediate = fopen(argv[2],"w"); // Missing check of argc and successful file open

    do
    {
      if (fscanf(source, "%9s", word) != 1)
      {
        printf("Illegal source file. START not found\n");
        fclose(source);
        fclose(intermediate);
        exit(1);
      }
    } while(strcmp(word, start) != 0);

    fscanf(source, "%x", &address);  // Missing check of return value being 1

    fprintf(intermediate, "%x", address);
    fprintf(intermediate, "%s", word);

    fclose(source);
    fclose(intermediate);

    return(0);
}

Finally notice that the code still miss important checks like the number of arguments supplied, successful file open and return value from fscan when scanning the address.

Upvotes: 1

Related Questions