summaryrefslogtreecommitdiff
path: root/examples/file/readwrite.c
blob: 8dc29837ef921b07b4355caffd7bc5c60b485958 (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
 * File      : readwrite.c
 * This file is part of RT-TestCase in RT-Thread RTOS
 * COPYRIGHT (C) 2010, RT-Thread Development Team
 *
 * The license and distribution terms for this file may be
 * found in the file LICENSE in this distribution or at
 * http://www.rt-thread.org/license/LICENSE
 *
 * Change Logs:
 * Date           Author       Notes
 * 2010-02-10     Bernard      first version
 */
#include <rtthread.h>
#include <dfs_posix.h>

#define TEST_FN		"/test.dat"

static char test_data[120], buffer[120];

/* �ļ���д���� */
void readwrite(const char* filename)
{
	int fd;
	int index, length;

	/* ֻд & ���� �� */
	fd = open(TEST_FN, O_WRONLY | O_CREAT | O_TRUNC, 0);
	if (fd < 0)
	{
		rt_kprintf("open file for write failed\n");
		return;
	}

	/* ׼��д������ */
	for (index = 0; index < sizeof(test_data); index ++)
	{
		test_data[index] = index + 27;
	}

	/* ����� */
	length = write(fd, test_data, sizeof(test_data));
	if (length != sizeof(test_data))
	{
		rt_kprintf("write data failed\n");
		close(fd);
		return;
	}

	/* �ر��ļ� */
	close(fd);

	/* ֻд����ĩβ���Ӵ� */
	fd = open(TEST_FN, O_WRONLY | O_CREAT | O_APPEND, 0);
	if (fd < 0)
	{
		rt_kprintf("open file for append write failed\n");
		return;
	}

	length = write(fd, test_data, sizeof(test_data));
	if (length != sizeof(test_data))
	{
		rt_kprintf("append write data failed\n");
		close(fd);
		return;
	}
	/* �ر��ļ� */
	close(fd);

	/* ֻ���򿪽�������У�� */
	fd = open(TEST_FN, O_RDONLY, 0);
	if (fd < 0)
	{
		rt_kprintf("check: open file for read failed\n");
		return;
	}

	length = read(fd, buffer, sizeof(buffer));
	if (length != sizeof(buffer))
	{
		rt_kprintf("check: read file failed\n");
		close(fd);
		return;
	}
	for (index = 0; index < sizeof(test_data); index ++)
	{
		if (test_data[index] != buffer[index])
		{
			rt_kprintf("check: check data failed at %d\n", index);
			close(fd);
			return;
		}
	}

	length = read(fd, buffer, sizeof(buffer));
	if (length != sizeof(buffer))
	{
		rt_kprintf("check: read file failed\n");
		close(fd);
		return;
	}
	for (index = 0; index < sizeof(test_data); index ++)
	{
		if (test_data[index] != buffer[index])
		{
			rt_kprintf("check: check data failed at %d\n", index);
			close(fd);
			return;
		}
	}
	/* ���������ϣ��ر��ļ� */
	close(fd);
	/* ��ӡ��� */
	rt_kprintf("read/write done.\n");
}

#ifdef RT_USING_FINSH
#include <finsh.h>
FINSH_FUNCTION_EXPORT(readwrite, perform file read and write test);
#endif