Read from file as char array

I extract from the file, and when I read it, it takes it line by line and prints it

what I want for sure, I want the char array to contain all the characters in the file and print it once,

this is the code i

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, sizeof(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 */
+3
source share
4 answers

You need to determine the file size. After that, you can select the array large enough and read it at a time.

There are two ways to determine the file size.

Usage fstat:

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

C fseekand 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);
}
+3
source

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

MapViewOfFile unix mmap.

( ) , . char[].

+2

, , , .

, . fseek(), , ftell(), , fseek() , . char malloc(), . fread() . , ().

0

. .

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

read .

count = read(fd,buf, bytecount)

.

0

Source: https://habr.com/ru/post/1748553/


All Articles