在C ++中,我尝试使用stdio.h(fopen,getc等)完全读取char,char。 我已经完成了一个程序,它创建一个资源管理器窗口并计算所选文件中的字母(和字节数)。 它似乎适用于.txt文件,但使用其他文件格式它不起作用。有人可以解释为什么以及如何解决它? 是否可以通过程序确定磁盘上的大小?
3源代码:
主要代码:
#include "OpenFileDialog.h"
#include <stdio.h>
#include <stdlib.h>
int main(void){
OpenFileDialog* openFileDialog1 = new OpenFileDialog();
openFileDialog1->FilterIndex = 1;
openFileDialog1->Flags |= OFN_SHOWHELP;
openFileDialog1->InitialDir = (TCHAR*)("C:\\Users\\Luca\\Documents");
openFileDialog1->Title = (TCHAR*)("Open Text File");
long long int number=0;
if (openFileDialog1->ShowDialog())
{
//MessageBox(0, openFileDialog1->FileName, "File selected",MB_OK | MB_ICONINFORMATION);
}
FILE * pFile;
char c;
int eofnbr=0;
int charnbr[256];
int otherschar=0;
char messageString1[2000];
char catString[200];
memset(charnbr,0,sizeof(messageString1));
memset(charnbr,0,sizeof(charnbr));
pFile = fopen(openFileDialog1->FileName,"r");
if (pFile==NULL){
return -1;
}
else{
int eofflag=0;
do{
do{
c = getc (pFile);
if((c>=0)&&(c<=255)){
charnbr[c]=charnbr[c]+1;
}
else
otherschar++;
if(c==EOF){
eofnbr++;
}
number++;
} while (c != EOF);
eofflag=feof(pFile);
} while(eofflag==0);
fclose (pFile);
for(int i=0;i<256;i=i+8){
sprintf(catString,"%d = %d\t%d = %d\t%d = %d\t%d = %d\t%d = %d\t%d = %d\t%d = %d\t%d = %d\n",i,charnbr[i],i+1,charnbr[i+1],i+2,charnbr[i+2],i+3,charnbr[i+3],i+4,charnbr[i+4],i+5,charnbr[i+5],i+6,charnbr[i+6],i+7,charnbr[i+7]);
strcat(messageString1,catString);
}
sprintf(catString,"others = %d\t EOF = %d\t\t%d Byte\n ",otherschar,eofnbr, number);
strcat(messageString1,catString);
}
MessageBox(0, messageString1, "File selected",MB_OK | MB_ICONINFORMATION);
return 0;
}
资源管理器功能:
#include "OpenFileDialog.h"
OpenFileDialog::OpenFileDialog(void)
{
this->DefaultExtension = 0;
this->FileName = new TCHAR[MAX_PATH];
this->Filter = 0;
this->FilterIndex = 0;
this->Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
this->InitialDir = 0;
this->Owner = 0;
this->Title = 0;
}
bool OpenFileDialog::ShowDialog()
{
OPENFILENAME ofn ;
TCHAR* explorerFolder= this->InitialDir;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = this->Owner;
ofn.lpstrDefExt = this->DefaultExtension;
ofn.lpstrFile = this->FileName;
ofn.lpstrFile[0] = '\0';
//ofn.lpstrFile = explorerFolder;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = this->Filter;
ofn.nFilterIndex = this->FilterIndex;
ofn.lpstrInitialDir = explorerFolder;
//ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle = this->Title;
ofn.Flags = this->Flags;
GetOpenFileName(&ofn);
if (_tcslen(this->FileName) == 0) return false;
return true;
}
资源管理器库:
#pragma once
#include <Windows.h>
#include <Commdlg.h>
#include <tchar.h>
class OpenFileDialog
{
public:
OpenFileDialog(void);
TCHAR* DefaultExtension;
TCHAR* FileName;
TCHAR* Filter;
int FilterIndex;
int Flags;
TCHAR* InitialDir;
HWND Owner;
TCHAR* Title;
bool ShowDialog();
};