读取并存储到两个数组中

时间:2016-03-05 18:36:50

标签: c arrays

目前我正在逐行阅读文档文件,但是我试图将信息存储在两个单独的数组中。

#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个阵列中。

1 个答案:

答案 0 :(得分: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;
}