开发者

read from file as char array

开发者 https://www.devze.com 2023-01-02 02:18 出处:网络
I am reaing from a file, and when i read, it takes it line by line, and prints it what i want exactly is i want an array of char holding all the chars in the file and print it once,

I am reaing from a file, and when i read, it takes it line by line, and prints it

what i want exactly is i want an array of char holding all the chars in the file and print it once,

this is the code i have

if(strcmp(str[0],"@")==0)
        {
            FILE *filecomand;
            //char fname[40];
            char line[100];
            int lcount;
            ///* Read in the filename */
            //printf("Enter the name of a ascii file: ");
            //fgets(History.txt, size开发者_开发知识库of(fname), stdin);

            /* Open the file.  If NULL is returned there was an error */
            if((filecomand = fopen(str[1], "r")) == NULL) 
            {
                    printf("Error Opening File.\n");
                    //exit(1);
            }
            lcount=0;
            int i=0;
            while( fgets(line, sizeof(line), filecomand) != NULL ) {
                /* Get each line from the infile */
                    //lcount++;
                    /* print the line number and data */
                    //printf("%s", line);  

            }

            fclose(filecomand);  /* Close the file */


You need to determine the size of the file. Once you have that, you can allocate an array large enough and read it in a single go.

There are two ways to determine the size of the file.

Using fstat:

struct stat stbuffer;
if (fstat(fileno(filecommand), &stbuffer) != -1)
{
    // file size is in stbuffer.st_size;
}

With fseek and ftell:

if (fseek(fp, 0, SEEK_END) == 0)
{
    long size = ftell(fp)
    if (size != -1)
    {
        // succesfully got size
    }

    // Go back to start of file
    fseek(fp, 0, SEEK_SET);
}


Another solution would be to map the entire file to the memory and then treat it as a char array.

Under windows MapViewOfFile, and under unix mmap.

Once you mapped the file (plenty of examples), you get a pointer to the file's beginning in the memory. Cast it to char[].


Since you can't assume how big the file is, you need to determine the size and then dynamically allocate a buffer.

I won't post the code, but here's the general scheme. Use fseek() to navigate to the end of file, ftell() to get size of the file, and fseek() again to move the start of the file. Allocate a char buffer with malloc() using the size you found. The use fread() to read the file into the buffer. When you are done with the buffer, free() it.


Use a different open. i.e.

fd = open(str[1], O_RDONLY|O_BINARY) /* O_BINARY for MS */

The read statement would be for a buffer of bytes.

count = read(fd,buf, bytecount)

This will do a binary open and read on the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消