Сортировать содержимое входного текстового файла и создать из него make qemu на языке c - PullRequest
0 голосов
/ 22 февраля 2020

Я хочу сделать следующее:

  1. разработать программу c таким образом, чтобы в терминале qemu должен быть создан исполняемый файл с именем sort.

  2. когда дано "sort sample.txt", он должен взять содержимое семпла и отсортировать текст внутри него в порядке возрастания.

  3. создать выходной файл и вывести его вывод.

Я сделал так:

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

   #define MAX_LEN 100 // Length of each line in input file.

   int main(void)
                 {
    char *strFileName = "C:\Users\sample\xv6-public\data.txt";
    char *strFileSummary = "C:\Users\sample\xv6-public\out.txt";
    char strTempData[MAX_LEN];
    char **strData = NULL; // String List
    int i, j;
    int noOfLines = 0;

    FILE * ptrFileLog = NULL;
    FILE * ptrSummary = NULL;

    if ( (ptrFileLog = fopen(strFileName, "r")) == NULL ) {
      fprintf(stderr,"Error: Could not open %s\n",strFileName);
     return 1;
    }
    if ( (ptrSummary = fopen(strFileSummary, "a")) == NULL ) {
      fprintf(stderr,"Error: Could not open %s\n",strFileSummary);
     return 1;
    }

    // Read and store in a string list.
    while(fgets(strTempData, MAX_LEN, ptrFileLog) != NULL) {
     // Remove the trailing newline character
     if(strchr(strTempData,'\n'))
        strTempData[strlen(strTempData)-1] = '\0';
    strData = (char**)realloc(strData, sizeof(char**)*(noOfLines+1));
    strData[noOfLines] = (char*)calloc(MAX_LEN,sizeof(char));
    strcpy(strData[noOfLines], strTempData);
    noOfLines++;
}
// Sort the array.
for(i= 0; i < (noOfLines - 1); ++i) {
    for(j = 0; j < ( noOfLines - i - 1); ++j) {
        if(strcmp(strData[j], strData[j+1]) > 0) {
            strcpy(strTempData, strData[j]);
            strcpy(strData[j], strData[j+1]);
            strcpy(strData[j+1], strTempData);
        }
    }
}
// Write it to outfile. file.
for(i = 0; i < noOfLines; i++)
    fprintf(ptrSummary,"%s\n",strData[i]);
// free each string
for(i = 0; i < noOfLines; i++)
    free(strData[i]);
// free string list.
free(strData);
fclose(ptrFileLog);
fclose(ptrSummary);
return 0;
 }

'' '

Но как добавить его в исполняемые файлы qemu?

Ответы [ 2 ]

0 голосов
/ 03 мая 2020

Это то, что я реализовал в своем репозитории xv6-publi c, написав код C и добавив его в системный вызов. Это сработало, спасибо за ваш вклад.

#include "types.h"
#include "stat.h"
#include "fcntl.h" // for using file defines
#include "user.h" // for using from strlen


void insertionSort(char *arr[], int n) 
{ 
   int i, j; 
   char *key;
   for (i = 1; i < n; i++) 
   { 
       key = arr[i]; 
       j = i-1; 
       while (j >= 0 && atoi(arr[j]) > atoi(key)) 
       { 
           arr[j+1] = arr[j]; 
           j = j-1; 
       } 
       arr[j+1] = key; 
   } 
} 

int main(int argc, char *argv[]) 
{
    if(argc != 6){
        printf(2, "sort: enter 5 numbers please.\n");
        exit();
    }

    int i;
    char* nums[5];
    for(i = 0 ; i < 5 ; i++)
        nums[i] = argv[i+1];
    insertionSort(nums, 5);
    printf(2,"proccess id is %d \n", getpid());
    int fd;
    if((fd = open("sorted.txt", O_CREATE | O_WRONLY)) < 0){
      printf(2, "sort: cannot open file");
      exit();
    }
    for(i = 0 ; i < 5 ; i++)
    {
        if(write(fd, nums[i], strlen(nums[i])) != strlen(nums[i])) {
            printf(2, "sort: write error\n");
            exit();
        }
        if(write(fd, "\n", 1) != 1) {
            printf(2, "sort: write error\n");
            exit();
        }
    }

    exit();
}
0 голосов
/ 22 февраля 2020

Вы копируете данные как сумасшедшие, даже перераспределяя строки с помощью MAX_LENGTH! в этом нет необходимости. Как вы можете забыть, что такое указатели!

char* temporary;
for(i= 0; i < (noOfLines - 1); ++i) {
    for(j = 0; j < ( noOfLines - i - 1); ++j) {
        if(strcmp(strData[j], strData[j+1]) > 0) {
           temporary=strData[j];
           strData[j]=strData[j+1];
           strData[j+1]=temporary;
        }
    }
}

Я не могу помочь вам с частью qemu, разве нет способа построить ее в соответствии с требуемой архитектурой и вставить PATH?

...