假设现在有txt文件如下,需要将里面每一项的内容分别读取并存储,以读取文件中的FrameNo、Y_bits以及Y_psnr三个变量为例进行分析。
txt文件下载:点击下载txt文件
完整C++程序如下:
txt_read.cpp
#include<iostream>
#include<iomanip>
using namespace std;
void errorMsg(const char *msg) {
printf("error:%s\n", msg);
#ifdef _WIN32
system("pause");
#endif
exit(-1);
}
void read_one_frame_info(int frameNo, int *y_bits, double *y_psnr, char *fileName) {
int frameno = 0, qp = 0, uv_bits = 0;
char temp[50];
char errorText[50];
FILE *fp;
fp = fopen(fileName, "r");
if (fp == NULL) {
sprintf(errorText, "File %s not found", fileName);
errorMsg(errorText);
}
while (!feof(fp))
{
fscanf(fp, "%s", temp);
if (strcmp(temp, "FrameNo:") == 0)
{
fscanf(fp, "%s", temp); // get frame number
frameno = atoi(temp);
if (frameno == frameNo)
{
break;
}
}
}
if (feof(fp))
{
sprintf(errorText, "In function read_one_frame_info: frame number %d not found", frameNo);
errorMsg(errorText);
}
fscanf(fp, "%s", temp);
fscanf(fp, "%s", temp); // get Y_bits
*y_bits = atoi(temp);
fscanf(fp, "%s", temp);
fscanf(fp, "%s", temp); // get UV_bits
fscanf(fp, "%s", temp);
fscanf(fp, "%s", temp); // get QP
fscanf(fp, "%s", temp);
fscanf(fp, "%s", temp); // get Y_psnr
*y_psnr = (float)atof(temp);
fclose(fp);
}
void main()
{
int frameNum = 100;
int *y_bit;
double *y_psnr;
y_bit = (int *)malloc(sizeof(int)*frameNum);
y_psnr = (double *)malloc(sizeof(double)*frameNum);
char *fileName = "per_frame_stat.txt";
for (int i = 0; i < frameNum; i++) {
read_one_frame_info(i, &y_bit[i], &y_psnr[i], fileName);
//普通输出
//cout << "FrameNo:" << i << " " <<
//"bitRate:" << y_bit[i] << " " << " PSNR:" << y_psnr[i] << endl;
//对齐输出
cout <<"FrameNo:"<< setw(10) << setfill(' ') << left <<i <<" "<<
"bitRate:" << setw(10) << setfill(' ') << left<<y_bit[i] << " " << " PSNR:" <<y_psnr[i] << endl;
}
}
注意:
cout设置对齐方式:..........<< setw(10) << setfill(' ') << left..........
对齐与非对齐方式运行结果如下,当然不同的宽度间隔可以灵活调整,也可以指定读取txt文件中的其它内容。
非对齐:
对齐: