这是我从控制台打开任何文件的代码。
但是,我不知道如何自动获取文件的宽度和高度。
#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;
}
最佳答案
width 和 high 是指文件的行数和列数吗?
在这种情况下,您可以检查换行符:
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);
另一方面,始终检查传递给 main
的参数数量和 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);
}
关于c - 在 C 中打开文件,但我不知道如何获取文件的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828877/