-
-
Save ZhigangPu/3f350e9791e79b8eb8995f465ec3c26e to your computer and use it in GitHub Desktop.
file operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int main(){ | |
FILE * fp; | |
char ch; | |
char str[10]; | |
if((fp = fopen("test.csv", "r"))==NULL){ | |
printf("文件打开失败!\n"); | |
exit(1); | |
}; | |
// fgetc 方法 | |
// while( ! feof(fp) ){ | |
// ch = fgetc(fp); | |
// printf("%c", ch); | |
// }; | |
// fgets 方法 | |
while( ! feof(fp) ){ | |
fgets(str, 10, fp); | |
printf("%s", str); | |
}; | |
fclose(fp); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
using namespace std; | |
int main(){ | |
const char * filename = "cat.jpg"; | |
ifstream infile; | |
infile.open(filename, ios::in|ios::binary); | |
// 检查是否打开成功 | |
if (!infile){ | |
cerr << "error: unable to open file" << endl; | |
return -1; | |
} | |
// 计算尺寸 | |
long l, m; | |
l = infile.tellg(); | |
cout << "begin pointer is " << l << endl; | |
infile.seekg(0, ios::end); | |
m = infile.tellg(); | |
cout << "end pointer is " << m << endl; | |
cout << "size of " << filename << " is " << m-l << " bytes" << endl; | |
infile.close(); | |
// 读入动态数组内, 并遍历输出 | |
long size; | |
char * buffer; | |
infile.open(filename, ios::in|ios::binary|ios::ate); | |
size = infile.tellg(); | |
infile.seekg(0, ios::beg); | |
buffer = new char [size]; | |
infile.read(buffer, size); | |
for(int i=0; i<size; i++){ | |
cout << "buffer" << i << " is: " << buffer[i] << endl; | |
} | |
delete [] buffer; | |
infile.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment