我写的一个设置文件大小的程序,程序逻辑:
命令行实现:(将指文件名称的文件设置为指定的大小):setfilesize 文件名 文件大小
程序实现:打开文件-->获取文件实际大小-->将文件指针移动到指定大小-实际大小
-->设置文件结束-->关闭文件.问题:运行程序以后,文件的大小被正确的设置了.但是文件的内容却是空的,连原来的内容都不见了.如果想要保留原来文件的内容,该怎样解决呢?#include <windows.h>
#include <stdio.h>
#include <assert.h>
#include <iostream.h>DWORD filter(DWORD excode)
{
return EXCEPTION_EXECUTE_HANDLER;
// return EXCEPTION_CONTINUE_SEARCH;
// return EXCEPTION_CONTINUE_EXECUTION;
}
int main(int argc,char **argv)
{
char c;
//read(0,&c,1);
HANDLE hstdin=GetStdHandle(STD_INPUT_HANDLE);
long filesize,tfilesize,offset;
if (argc!=3){
printf("useage:setfilesize filename filesize\n");
cin>>c;
return 1;
}
HANDLE hFile=CreateFile(argv[1],GENERIC_WRITE|GENERIC_READ,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile==INVALID_HANDLE_VALUE){
perror("createfile");
cin>>c;
return 1 ;
}

_try{
filesize=atoi(argv[2]);
}
_except(filter(GetExceptionCode())){
printf("input filesize error");
cin>>c;
exit(1);
}
if((tfilesize=SetFilePointer(hFile,0,NULL,FILE_END))==0xFFFFFFFF){
perror("getfilesize error");
cin>>c;
return 1;
}
offset=filesize-tfilesize;
if(SetFilePointer(hFile,offset,NULL,FILE_END)==0xFFFFFFFF){
perror("setfilepointer");
cin>>c;
return 1;
}
if(!SetEndOfFile(hFile)){
perror("setendoffile");
cin>>c;
return 1;
}

CloseHandle(hFile);
printf("setfilesize successful!\n");
cin>>c;
return 0;

}

解决方案 »

  1.   

    打开文件-->读取文件指定大小的数据-->重新将数据写入文件-->关闭文件
      

  2.   

    CreateFile(argv1],GENERIC_WRITE|GENERIC_READ,0,NULL,
               CREATE_ALWAYS,        // 应该是这里有问题
               FILE_ATTRIBUTE_NORMAL,
               NULL);
    CREATE_ALWAYS: Creates a new file. If the file exists, the function overwrites the file, clears the existing attributes, and combines the file attributes and flags specified by dwFlagsAndAttributes with FILE_ATTRIBUTE_ARCHIVE。
    建议你用OPEN_EXISTING。