1. 程式人生 > >一個將當前目錄下HEX檔案的第一行資料刪除的程式

一個將當前目錄下HEX檔案的第一行資料刪除的程式

為什麼要寫這樣一個函式

在使用SoftConsole開發M3程式時,生成的hex檔案,必須要把第一行資料刪除,才能在Libero中使用,所以寫了這個小工具,這是2.0版本了,第一版是直接刪除第一行資料,有可能會導致誤操作。

實現原理

主要使用到了bat批處理命令和檔案IO操作。

  1. 建立bat批處理檔案,內容為dir *.hex /b>hex_file_name.txt
  2. 執行bat命令,這個命令能將當前目錄下的hex檔案的名稱如filename.hex存入到txt檔案中
  3. 開啟存有hex檔名的txt檔案
  4. 讀取hex檔案
  5. 讀取每一個字元,當讀取到換行時,即讀取到第一行結束,將以後的字元寫入到新的hex檔案中,直到檔案結束
  6. 刪除其他的檔案,只保留新的hex檔案。

執行環境

Code::Blocks 17.12

程式碼實現:


#include "stdio.h"

#include "stdlib.h"

#include "unistd.h"

#include "string.h"

#include "conio.h"

#include<windows.h>

int main()
{
    FILE *fin,*fout, *fbat, *fhexname;
    int c, i=0;
    char bat_cmd[] = "dir *.hex /b>hex_file_name.txt"
; char hex_name[50]; char cmd_in; printf("\n\n功能:將當前目錄下SoftConsole所生成的hex檔案刪除第一行資料,檔名不限——v1.3\n\n"); printf("當前目錄下的hex檔案是新生成的嗎? y/n"); while(1) { cmd_in = getch(); if (cmd_in == 'y') { system("cls"); break; } else
return 0; } fbat=fopen("get_hex_filename.bat","w"); fprintf(fbat, "dir *.hex /b>hex_file_name.txt"); //將bat檔案內容寫入檔案 fclose(fbat); system("get_hex_filename.bat"); //執行bat,得到儲存hex檔名稱的txt檔案 fhexname = fopen("hex_file_name.txt", "r"); //開啟txt檔案 while (1) { hex_name[i++] = fgetc(fhexname);//讀取每一個字元 if ('\n'==hex_name[i-2]) //讀取到第一行換行 break; } hex_name[i-2] = '\0'; fin=fopen(hex_name,"r"); //讀取hex檔案 fout=fopen("hex_temp.hex","w"); //開啟.tmp準備寫 while (1) { c=fgetc(fin); //讀取每一個字元 if (EOF==c) //如果檔案結束 break; if ('\n'==c) //如果讀取到換行,為第一行 break; } if (EOF!=c) //如果不是檔案結束 while (1) { c=fgetc(fin); if (EOF==c) //將第一行換行後的字元寫入到新檔案 break; fputc(c,fout); } fclose(fin); //必須先關閉,否則佔用不能刪除 fclose(fout); fclose(fhexname); remove(hex_name); //刪除原始檔 remove("get_hex_filename.bat"); remove("hex_file_name.txt"); rename("hex_temp.hex",hex_name); //新檔案重新命名 printf("\n\n功能:將當前目錄下SoftConsole所生成的hex檔案刪除第一行資料,檔名不限——v1.3\n\n"); printf("\n當前目錄下的%s檔案的第1行資料已經刪除!\n",hex_name); printf("\n注:每執行一次就會刪除第1行資料!\n\n"); printf("按任意鍵退出此程式。。。\n"); getch(); }

測試檔案test.hex


Microsemi SoftConsole delete hex file line 24
Microsemi SoftConsole delete hex file line 25
Microsemi SoftConsole delete hex file line 26
Microsemi SoftConsole delete hex file line 27
Microsemi SoftConsole delete hex file line 28
Microsemi SoftConsole delete hex file line 29
Microsemi SoftConsole delete hex file line 30
Microsemi SoftConsole delete hex file line 31
Microsemi SoftConsole delete hex file line 32
Microsemi SoftConsole delete hex file line 33
Microsemi SoftConsole delete hex file line 34
Microsemi SoftConsole delete hex file line 35
Microsemi SoftConsole delete hex file line 36
Microsemi SoftConsole delete hex file line 37
Microsemi SoftConsole delete hex file line 38
Microsemi SoftConsole delete hex file line 39
Microsemi SoftConsole delete hex file line 40
Microsemi SoftConsole delete hex file line 41
Microsemi SoftConsole delete hex file line 42

檔案下載

執行結果:

歡迎大家關注我的個人部落格 或微信掃碼關注我的公眾號

不定期更新個人學習筆記和技術總結,歡迎大家互相學習交流!