Skip to content

Instantly share code, notes, and snippets.

@ZhigangPu
Created October 29, 2019 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZhigangPu/3f350e9791e79b8eb8995f465ec3c26e to your computer and use it in GitHub Desktop.
Save ZhigangPu/3f350e9791e79b8eb8995f465ec3c26e to your computer and use it in GitHub Desktop.
file operation
#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);
}
#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