1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <dirent.h>
17 #include <fcntl.h>
18 #include <sys/stat.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include "test.h"
23
24 /**
25 * @tc.name : renameat_0100
26 * @tc.desc : When newname already exists, test the renameat function
27 * @tc.level : Level 0
28 */
renameat_0100(void)29 void renameat_0100(void)
30 {
31 int oldfd, newfd;
32 char oldPath[] = "/data/renameat.txt";
33 char newPath[] = "/data/newrenameat.txt";
34 const char *msg = "test code";
35 int len = strlen(msg);
36 char buf[1024] = {0};
37
38 if ((oldfd = creat(oldPath, S_IWUSR)) < 0) {
39 t_error("%s creat oldfd failed\n", __func__);
40 }
41 if ((newfd = creat(newPath, S_IWUSR)) < 0) {
42 t_error("%s creat newfd failed\n", __func__);
43 }
44 close(oldfd);
45 close(newfd);
46 oldfd = open(oldPath, O_RDWR);
47 int wresult = write(oldfd, msg, len);
48 if (wresult != len) {
49 t_error("%s write get result is %d not want %d\n", __func__, wresult, len);
50 }
51 close(oldfd);
52 if (renameat(oldfd, oldPath, newfd, newPath) == -1) {
53 t_error("%s renameat failed\n", __func__);
54 return;
55 }
56 newfd = open(newPath, O_RDWR);
57 int bytes = read(newfd, buf, len);
58 if (bytes == -1) {
59 t_error("%s read file failed\n", __func__);
60 return;
61 }
62 if (strcmp(msg, buf)) {
63 t_error("%s wrong string written to file\n", __func__);
64 return;
65 }
66 close(newfd);
67 remove(newPath);
68 }
69
main(int argc,char * argv[])70 int main(int argc, char *argv[])
71 {
72 renameat_0100();
73 return t_status;
74 }