2016-03-05 81 views
-1

目前我正在逐行閱讀文檔文件,但我試圖存儲在兩個單獨的數組中給出的信息。讀取和存儲到兩個數組

#include <stdio.h> 
int preprocess_get_line(char label[], char instruction[256], FILE* fp); 

int main(int argc, char *argv[]) 
{ 
/* Open file and check success */ 
    char *filename = "hello.asm"; 
    if (argc >1) 
{ 
     filename = argv[1]; 
} 
    FILE* inputfile = fopen(filename, "r"); 
    char label[9]; 
    char instruction [256]; 

    if(inputfile == NULL) 
{ 
    fprintf(stderr, "Unable to open \"%s\"\n", filename); 
    return 1; 
} 

while (preprocess_get_line(label,instruction, inputfile) !=EOF) 
/*im trying to store this information into 2 arrays*/ 
for (int i = 0; i<10; i++) 
    char [j] = ':' 
{ 
     if (i == '-') 
     { 
     j<i 
     label [j] = j 
     } 
    printf("%s: %s", label, instruction); 
} 
    return 0; 
} 

int preprocess_get_line(char label[], char instruction[], FILE* fp) 
{ 

char str[256]; 
if(fgets(str, 256, fp) == NULL) 
{ 
    fclose(fp); 
    return EOF; 
} 
} 

我想要讀的是文本行的例子,

main: mov %a,0x04   - sys_write 

我想存儲,標籤和任何與第一位 - 即時試圖存儲在指令中。 我目前正在努力將它存儲在2個數組中。

+0

這甚至不會編譯。在預讀好的情況下,'preprocess_get_line()'返回什麼? –

回答

0

我不知道究竟你想達到什麼樣的,但也許這將幫助你:

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

#define LABEL_SIZE 9 
#define INSTRUCTION_SIZE 256 

int preprocess_get_line(char label[], char instruction[256], FILE* fp); 

int main(int argc, char* argv[]) 
{ 
    char* filename = "hello.asm"; 

    if(argc > 1) 
    { 
     filename = argv[1]; 
    } 

    FILE* inputfile = fopen(filename, "r"); 

    if(inputfile == NULL) 
    { 
     fprintf(stderr, "Unable to open \"%s\"\n", filename); 
     return 1; 
    } 

    char label[LABEL_SIZE] = {0}; 
    char instruction[INSTRUCTION_SIZE] = {0}; 
    char* line = NULL; 
    size_t line_len; 
    while(getline(&line, &line_len, inputfile) != EOF) 
    { 
     char* pos = strchr(line, ':'); 
     if(pos == NULL) 
     { 
      free(line); 
      continue; 
     } 

     int to_copy = pos - line; 
     if(to_copy >= LABEL_SIZE) 
      to_copy = LABEL_SIZE - 1; 
     strncpy(label, line, to_copy); 
     strcpy(instruction, pos); 

     printf("label: %s\ninstruction: %s", label, instruction); 
     free(line); 
     line = NULL; 
     memset(label, '\0', LABEL_SIZE); 
     memset(instruction, '\0', INSTRUCTION_SIZE); 
    } 

    free(line); 

    fclose(inputfile); 

    return 0; 
}