C/C++ snippets 程式碼片段

以下紀錄我常用的程式碼片段

除錯類

請看這篇文章

自己的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void readFromFile(const char *filename)
{
char buf[128];
FILE *fp = NULL;
int ret;
float num[3];

fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: can not read %s file!\n", filename);
return;
}

while (1) {
ret = fscanf(fp, "%f, %f, %f", &num[0], &num[1], &num[2]);
if (ret == EOF)
break;
}

if (fp != NULL)
fclose(fp);
}

別人的

http://www.roxlu.com/2013/014/c—file-operation-snippets

Open a file in binary mode

1
2
3
4
5
6
std::ifstream ifs;
ifs.open("input.bin", std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
printf("Error trying to open the file.\n");
::exit(EXIT_FAILURE);
}

讀取二進制檔到現存的 std::vector (Reading a binary file into an existing std::vector)

1
2
3
4
5
6
7
std::ifstream ifs;
ifs.open("input.bin", std::ios::in | std::ios::binary);

std::vector<char> buffer;
buffer.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());

ifs.close();

讀取文字檔到 buf 裡 (Reading a text file into a string (note the extra parathesis for std::istreambuf_iterator))

1
2
3
4
5
6
std::ifstream ifs(filepath.c_str(), std::ios::in);
if(!ifs.is_open()) {
return false;
}

std::string str( (std::istreambuf_iterator<char>(ifs)) , std::istreambuf_iterator<char>());

Reading a text file using pure C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int read_file(const char* path, char* buf, int len) {
/* try to open the file */
FILE* fp = fopen(path, "r");
if (!fp) {
printf("Error: cannot read file: %s\n", path);
return -1;
}

/* find size */
long size = 0;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);

if (size > len) {
printf("Error: file size it too large for given buffer. We need: %ld bytes.\n", size);
fclose(fp);
return -2;
}

size_t r = fread(buf, size, 1, fp);
if (r != 1) {
printf("Error: cannot read file into buffer.\n");
fclose(fp);
return -3;
}

return (int)size;
}

檔案大小 (Check the file size)

1
2
3
ifs.seekg(0, std::ifstream::end);
size_t fsize = ifs.tellg();
printf("File size: %ld.\n", fsize);

跳至某位置 (Jump to a position)

1
2
3
4
5
ifs.seekg(1024, std::ios_base::beg);     
if (!ifs) {
printf("Error trying to jump to a position.\n");
::exit(EXIT_FAILURE);
}

取得現在位置 (Get the curent position)

1
2
size_t pos = ifs.tellg();
printf("Current position: %ld.\n", pos);

Jump to a absolute position

1
ifs.seekg(0, std::ios_base::beg);

Read some bytes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const size_t buffer_size = 1024 * 1024 * 10;
char* buffer = new char[buffer_size];

size_t read_size = buffer_size;
if(fsize < read_size) {
read_size = fsize;
printf("The file is smaller then the number buffer.\n");
}

printf("Reading: %ld\n", read_size);
ifs.read(buffer, read_size);
if(!ifs) {
printf("Error trying to into buffer.\n");
exit(EXIT_FAILURE);
}

if(ifs.gcount() != sizeof(buffer)) {
printf("Number of bytes is not the same as requested.\n");
}
printf("Read: %ld bytes into buffer\n", ifs.gcount());

delete[] buffer;
buffer = NULL;

讀取二進制檔 (Read all bytes)

1
2
3
4
5
6
7
8
9
10
11
12
13
do {
ifs.read((char*)buffer, sizeof(buffer));
nread = ifs.gcount();
for (size_t i = 0; i < nread; ++i) {
sprintf(hexbuf, "0x%02x", buffer[i]);
ofs_source << hexbuf << ", ";
++nchars_written;
if (nchars_written >= 16) {
ofs_source << "\n ";
nchars_written = 0;
}
}
} while (ifs.good());

寫入二進制檔 (Write some bytes)

1
2
3
4
5
6
7
8
std::vector<char> buffer;
buffer.push_back('a');
buffer.push_back('b');
buffer.push_back('c');

std::ofstream ofs("output.bin", std::ios::out | std::ios::binary);
ofs.write(&buffer.front(), buffer.size());
ofs.close();

Write the contents of a std::stringstream to a file

1
2
3
4
5
6
7
8
9
10
11
std::ofstream ofs("output.txt", std::ios::out);
if(!ofs.is_open()) {
return;
}

std::stringstream ss;
ss << "some content.";

ofs << ss.rdbuf();

ofs.close();

And the complete source:

Compile with:

1
g++ main.cpp -g -o out && ./out

Complete source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <fstream>
#include <stdio.h>

int main() {

// open a file in binary mode
std::ifstream ifs;
ifs.open("test.mov", std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
printf("Error trying to open the file.\n");
::exit(EXIT_FAILURE);
}

// check the file size
ifs.seekg(0, std::ifstream::end);
size_t fsize = ifs.tellg();
printf("File size: %ld.\n", fsize);


// jump to a position from the start of the file
ifs.seekg(1024, std::ios_base::beg);
if (!ifs) {
printf("Error trying to jump to a position.\n");
::exit(EXIT_FAILURE);
}

// get current position
size_t pos = ifs.tellg();
printf("Current position: %ld.\n", pos);


// go back to the beginning of the file.
ifs.seekg(0, std::ios_base::beg);

// read some bytes
const size_t buffer_size = 1024 * 1024 * 10;
char* buffer = new char[buffer_size];

size_t read_size = buffer_size;
if (fsize < read_size) {
read_size = fsize;
printf("The file is smaller then the number buffer.\n");
}

printf("Reading: %ld\n", read_size);
ifs.read(buffer, read_size);
if (!ifs) {
printf("Error trying to into buffer.\n");
exit(EXIT_FAILURE);
}

if (ifs.gcount() != sizeof(buffer)) {
printf("Number of bytes is not the same as requested.\n");
}
printf("Read: %ld bytes into buffer\n", ifs.gcount());

delete[] buffer;
buffer = NULL;
return 0;
}

其它相關文章推薦
C/C++ 新手入門教學懶人包
C/C++ 常見的各種程式碼風格