简体   繁体   中英

open file in C and I don't know how do I get the width and height of the file

This is my code to open any file from the console.
But, I don't know how I get the width and height of the file automatically.

#include <stdio.h>
int main(int argc, char *argv[]){
        char dat;
        FILE *fs;
        fs = fopen(argv[1], "r");

        while((dat = fgetc(fs))!=EOF){ 
                printf("%c",dat);
        } 

        fclose(fs);

        printf("\n");
        return 0;
}

With width and high you mean the number of rows and columns of the file?

In this case you can check the newline character:

int rows = 0;
int cols = 0;
int rowcols = 0;
while ((dat = fgetc(fs)) != EOF) {
    if (dat == '\n') {
        if (rowcols > cols) {
            cols = rowcols;
        }
        rowcols = 0;
        rows++;
    } else {
        if (dat != '\r') { /* Do not count the carriage return */
            rowcols++;
        }
    }
    printf("%c",dat); 
}
/* If the file does not end with a newline */
if (rowcols != 0) {
    if (rowcols > cols) {
        cols = rowcols;
    }
    rows++;
}
printf("Rows = %d, Cols = %d\n", rows, cols); 

On the other hand, always check the number of arguments passed to main and the result of fopen :

if (argc < 2) {
    fprintf(stderr, "Usage = %s file\n", argv[0]);
    exit(EXIT_FAILURE);
}
...
fs = fopen(argv[1], "r");
if (fs == NULL) {
    perror("fopen");
    exit(EXIT_FAILURE);
}

Here is the sample code. explanation I wrote in comments

int main(int argc, char *argv[]){
        FILE *fs;
        fs = fopen(argv[1], "r");
        /* always check return value of fopen() */
        if(fs == NULL) {
                /* put some mesage */
                return 0;
        }
        /* width width means which lines having max no of characters */
        /* step-1 : use fgets() bcz it read line by line */

        char buf[100];/* assuming each line have less than 100 char */
        int width = 0,len = 0,height = 0;
        while(fgets(buf,sizeof(buf),fs)) {
                /* now buf having one line, your job is find the length of each line
                   and do comparison mechanism */
                len = strlen(buf);
                if(width < len) {
                        width = len;
                }
                height++;/* its height bcz when above loop fails 
                            height value is nothing but no of line in file*/
        }
        printf("width = %d and height = %d \n",width,height );
        fclose(fs);
        return 0;
}

To know how fgets() works. open man 3 fgets from command line & check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM