1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3// See the LICENSE file in the project root for more information.
4
5/*============================================================================
6**
7** Source: test1.c
8**
9** Purpose: Write a short string to a file and check that it was written
10** properly.
11**
12**
13**==========================================================================*/
14
15#include <palsuite.h>
16
17int __cdecl main(int argc, char **argv)
18{
19 const char filename[] = "testfile.tmp";
20 const char outBuffer[] = "This is a test.";
21 char inBuffer[sizeof(outBuffer) + 10];
22 int itemsExpected;
23 int itemsWritten;
24 FILE * fp = NULL;
25
26 if (PAL_Initialize(argc, argv))
27 {
28 return FAIL;
29 }
30
31 if((fp = fopen(filename, "w")) == NULL)
32 {
33 Fail("Unable to open a file for write.\n");
34 }
35
36 itemsExpected = sizeof(outBuffer);
37 itemsWritten = fwrite(outBuffer,
38 sizeof(outBuffer[0]),
39 sizeof(outBuffer),
40 fp);
41
42 if (itemsWritten == 0)
43 {
44 if(fclose(fp) != 0)
45 {
46 Fail("fwrite: Error occurred during the closing of a file.\n");
47 }
48
49 Fail("fwrite() couldn't write to a stream at all\n");
50 }
51 else if (itemsWritten != itemsExpected)
52 {
53 if(fclose(fp) != 0)
54 {
55 Fail("fwrite: Error occurred during the closing of a file.\n");
56 }
57
58 Fail("fwrite() produced errors writing to a stream.\n");
59 }
60
61 if(fclose(fp) != 0)
62 {
63 Fail("fwrite: Error occurred during the closing of a file.\n");
64 }
65
66 /* open the file to verify what was written to the file */
67 if ((fp = fopen(filename, "r")) == NULL)
68 {
69 Fail("Couldn't open newly written file for read.\n");
70 }
71
72 if (fgets(inBuffer, sizeof(inBuffer), fp) == NULL)
73 {
74 if(fclose(fp) != 0)
75 {
76 Fail("fwrite: Error occurred during the closing of a file.\n");
77 }
78
79 Fail("We wrote something to a file using fwrite() and got errors"
80 " when we tried to read it back using fgets(). Either "
81 "fwrite() or fgets() is broken.\n");
82 }
83
84 if (strcmp(inBuffer, outBuffer) != 0)
85 {
86 if(fclose(fp) != 0)
87 {
88 Fail("fwrite: Error occurred during the closing of a file.\n");
89 }
90
91 Fail("fwrite() (or fgets()) is broken. The string read back from"
92 " the file does not match the string written.\n");
93 }
94
95 if(fclose(fp) != 0)
96 {
97 Fail("fwrite: Error occurred during the closing of a file.\n");
98 }
99
100 PAL_Terminate();
101 return PASS;
102}
103
104
105