c-如何使用sscanf直接从字符串中输入整数值(从文件中读取)



我正试图编写一段代码,读取PPM文件的"头"。例如:

P3
400 200
255

在这种情况下,宽度为400,高度为200,最大颜色值为255。我试图将这些字符串值分配为整数,但我认为有一种更好的方法可以用更少的行和更"安全"的行来实现这一点。我如何避免使用atoi((函数?(注意,我已经在我的实际代码中包含了"检查文件是否可打开"部分,这只是一个简化的片段(

char buffer[200];
char height[200];
char width[200];
char maxColour[200];
FILE *file = fopen("mcmaster.ppm", "r");
fgets(buffer, sizeof(buffer), file); // File format line
fgets(buffer, sizeof(buffer), file); // Width x height line
sscanf(buffer, "%s %s", width, height);
fgets(buffer, sizeof(buffer), file); // Max colour line
sscanf(buffer, "%s", maxColour);
int actHeight = atoi(height);
int actWidth = atoi(width);
int actMaxColour = atoi(maxColour);

我建议您使用fscanf而不是sscanf。首先,定义一个"错误函数"来验证读取文件的问题,如

void fscanf_Error(char *file)
{
fprintf(stderr,"Error reading file: %sn. Exiting(1).n ",file);
exit(1);
}

然后

char dummy[12];
if(!fscanf(file, "%sn", dummy))
fscanf_Error(file);
if(!fscanf(file," %d %dn", width, height))
fscanf_Error(file);
if(!fscanf(file, "%dn", maxColour))
fscanf_Error(file);

最新更新