代碼:
1 #include <stdio.h> 2 #include <string.h> 3 #include <fcntl.h> 4 /*************基本的函數API******************** 5 int open(const char *pathname, int oflag, int perms) 6 oflag: 7 O_RDONLY 只讀 8 O_WRONLY 只寫 9 O_RDWR 讀寫 10 O_APPEND 追加 11 O_CREAT 創建 12 O_EXCL 測試 13 O_TRUNC 刪除 14 perms: 15 被打開的文件的存取權限,采用8進制 16 int close(int fd) 17 ssize_t read(int fd, void *buf, size_t count) 18 fd: 19 文件描述符 20 buf: 21 指定存儲器讀取數據的緩沖區 22 count: 23 指定讀取數據的字節數 24 ssize_t write(int fd, void *buf, size_t count) 25 fd: 26 文件描述符 27 buf: 28 指定存儲器讀取數據的緩沖區 29 count: 30 指定讀取數據的字節數 31 off_t lseek(int fd, off_t offset, int whence) 32 fd: 33 文件描述符 34 offset: 35 偏移量,每一讀寫操作需要移動的字節數,可向前、可向后 36 count: 37 當前位置的基點: 38 SEEK_SET(當前位置是文件的開頭) 39 SEEK_CUR(當前位置為文件指針的位置,新位置為當前位置加上偏移量) 40 SEEK_END(當前位置問文件的尾部,新位置為文件大小加上偏移量的大小) 41 **********************************************/ 42 int main(void) 43 { 44 int fd,len; 45 char *buf = "Hello World!\n",Out[30]; 46 fd = open("a.txt", O_CREAT | O_TRUNC | O_RDWR, 0600); 47 printf("open file:a.txt fd = %d\n", fd); 48 len = strlen(buf); 49 int size = write(fd, buf, len); 50 close(fd); 51 //Begin to read the file 52 fd = open("a.txt", O_RDWR, 0600); 53 lseek(fd, 0, SEEK_SET); //Before to read the file,you should call the function to make the fd point to begin of files 54 size = read(fd, Out, 12); 55 printf("size = %d\nread from file:\n %s\n",size,Out); 56 close(fd); 57 return 0; 58 }
實例1 讀取一張通過MATLAB讀取JPG圖片轉換成TXT文本的文件內容:
首先圖像是這樣的lena.jpg:
通過MATALB讀取進去之后,轉換成灰度圖像,如下所示處理結果如上圖所示:
I = imread('F:\Leanring\C\Learning\lena.jpg'); Gray = rgb2gray(I); imshow(Gray)
接下來我們在變量一欄中,復制粘貼所有的數據到TXT文本當中,如下所示:
MATLAB數據 文本數據
這樣,我們通過分析文本中的數據分布格式,首先,文本擋住的所有數據都是只包含了圖像的數據的,不包括了JPG圖片格式相關的數據內容,其次,在我們復制粘貼的過程中的每兩個數據之間的分隔方式都是通過TAB鍵來分隔的,同樣的在每一行數據的結尾部分,都是通過回車鍵\t或者換行符\n來結尾的,所以根據這樣的數據格式,我們設計如下的讀取對應文本內容的C語言函數API,這里的TAB在ASCII的編碼數據是:9 同樣的,\t和\n的ASCII的編碼是10和13,這樣的話,通過if就能隔離開數據。
void ImageReadFromTXT(int *data,int width,int height,char *dir) { FILE *Pic; int D=0,count=0,Bit[3]={0},i,j; Pic = fopen(dir,"rb"); for(i=0;i<height;i++) { D = 0; for(j=0;j<width;j++) { count = 0; Bit[0] = 0; Bit[1] = 0; Bit[2] = 0; D = 0; while(1) { fread(&D,sizeof(char),1,Pic); if(D == 9 || D == 10 || D == 13) break;// D == 9 Bit[count] = D-48; count++; } *(data+i*width+j) = Bit[0]*100+Bit[1]*10+Bit[2]; } } fclose(Pic); }
主函數內容如下:

1 /*********************************************************** 2 從TXT文件中讀取一個圖片文件的數據,圖片文件的數據首先通過 3 MATLAB讀取到變量中,然后復制粘貼到TXT文件當中處理。 4 ***********************************************************/ 5 int width=300; 6 int height =300; 7 int data[width][height]; 8 ImageReadFromTXT(data,width,height,"lena.txt"); 9 printf("The first data is:%d\n",data[0][0]); 10 printf("The first data is:%d\n",data[0][1]); 11 printf("The first data is:%d\n",data[0][2]); 12 printf("The first data is:%d\n",data[0][3]);
實驗結果: