Search code examples
cstrtokstrcpyatoi

Using read() and putting the buffer into a string


this is my second question as i've had trouble with the first one due to this problem. I have a file which i have to read using the read() statment, no no fget() or fread() etc i use the line.

read(fileRead, buffer, blocksize);

where as you know fileRead is my filedescriptor, buffer is an unsigned char and blocksize is the size of buffer (i chose 32); my problem is i have a loop which runs until the file ends and takes a buffer of the file (32) and i need to put that into a string.

So i was wondering if you could help me with the line of code which would take the buffer and append it to a string (not 2D array, this won't be good) I have tried

openCopyClose(int argc, char ** argv)
{
    int i=0,j=0, k=0, count = 0;
    size_t blocksize = 32;
    char fromFile[256], newFile[1000][100], string[100000];
    int fileRead;
    unsigned char buffer[blocksize];
    ssize_t status;

    strcpy(fromFile, argv[1]);

    fileRead = open(fromFile, O_RDONLY);  // open for reading

    status = 99;
    while (status > 1)        //while not EOF or error
    {
        status = read(fileRead, buffer, blocksize);
        strcpy(newFile[i], buffer);

        for(count = 0; count<= 32; count++)
        {
            buffer[count] = 0;
        }
        i ++;                   

        if(status < 0)
        {
            printf("oops2\n");
            exit(1);
        }

    }
    printf("\n");

    for(j = 0; j < i; j++)
    {
        printf("%s", newFile[j]);
    }          
    close(fileRead);

}

But this will not work when i try to strtok it to put it in a structure. I need that file into one string using read() any ideas?

my code for the strtok afterwards will need to look something like this

struct processStruct processes[700];
while(count < 701)
{

    processes[count].processNumber = strtok(newFile[0], " \n");
    processes[count].quanta = atoi(strtok(NULL, " \n"));
    processes[count].priority = atoi(strtok(NULL, " \n"));

    count ++;
}

thank you


Solution

  • i solved how to put the File into a string, it was relatively simple, i'm surprised i missed it

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

    and now to put it in the struct.....