0
votes

i'm pretty new to forums so i hope i don't mess up. I have a program that reads from a file, so far it puts the file into a 2D char array. I now need to strtok the 2D 'string' and place each part into a struct

here is the code

struct processes                 
{ 
    char processNumber[20]; 
    int quanta; 
    int priority; 
}process; 

and

   int readSave(int argc, char ** argv)
{
int i,j,k,count;
size_t blocksize = 16;
char originalFile[256], newFile[1000][20];
int fileDes;
ssize_t status;
unsigned char buffer[blocksize];


strcpy(originalFile, argv[1]);

fileDes = open(originalFile, O_RDONLY); // open for reading

i=0;
status = 99;
while(status > 0 )  // while no error
{
    status = read(fileDes, buffer, blocksize);
    strcpy(newFile[i],buffer); //line 71

    for(k = 0; k <= blocksize; k++)
    {
        buffer[k] = 0;
    }
    i++;

    if(status < 0)
    {
        printf("\nERROR\n");
        exit(6);
    }   
}

//remove later
for(j = 0; j < i; j++) // prints out string to make sure it was input properly
{
    printf("%s", newFile[j]);
}

printf("\n");
close(fileDes);

//Don't know how to carry on

}

I hope you can help because i'm lost EDIT struct processStruct processes[7000]; while(newFile != NULL) { strcpy(processes[count].processNumber, strtok(newFile[count], " \n")); processes[count].quanta = atoi(strtok(NULL, " \n")); processes[count].priority = atoi(strtok(NULL, " \n"));

    count ++;
}

i changed the struct and input given by @Igor but when i run it, i get a segmentation fault and when i compile with -Wall i get readtostring.c: In function ‘readSave’: readtostring.c:71:3: warning: pointer targets in passing argument 2 of ‘strcpy’ differ in signedness [-Wpointer-sign] /usr/include/string.h:128:14: note: expected ‘const char * restrict’ but argument is of type ‘unsigned char *’

1

1 Answers

1
votes

Issue 1:

Seems like you should do strtok(newFile[something], " \n") and not strtok(newFile, " \n"). And don't forget to do something++ in each iteration.


Issue 2:

You can't strcpy to int. Try instead:

process[something].quanta = atoi(strtok(NULL, " \n"));
process[something].priority = atoi(strtok(NULL, " \n"));

Issue 3:

process is a struct and not array of structs, so you can't do process[something]. Did you mean to create an array of structs: processes process[20];