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: Writes a simple file and calls fgets() to get a string shorter
10** than the first line of the file. Verifies that the correct
11** string is returned.
12**
13**
14**==========================================================================*/
15
16#include <palsuite.h>
17
18int __cdecl main(int argc, char **argv)
19{
20 const char outBuf1[] = "This is a test.\n";
21 const char outBuf2[] = "This is too.";
22 char inBuf[sizeof(outBuf1) + sizeof(outBuf2)];
23 const char filename[] = "testfile.tmp";
24 const int offset = 5; /* value chosen arbitrarily */
25 int actualLen;
26 int expectedLen;
27 FILE * fp;
28
29 if (PAL_Initialize(argc, argv))
30 {
31 return FAIL;
32 }
33
34
35 /*write the file that we will use to test */
36 fp = fopen(filename, "w");
37 if (fp == NULL)
38 {
39 Fail("Unable to open file for write.\n");
40 }
41
42 fwrite(outBuf1, sizeof(outBuf1[0]), sizeof(outBuf1), fp);
43 fwrite(outBuf2, sizeof(outBuf2[0]), sizeof(outBuf2), fp);
44
45 if (fclose(fp) != 0)
46 {
47 Fail("Error closing a file opened for write.\n");
48 }
49
50
51 /*now read back the entire first string*/
52 fp = fopen(filename, "r");
53 if (fp == NULL)
54 {
55 Fail("Unable to open file for read.\n");
56 }
57
58 /*note: +1 because strlen() returns the length of a string _not_
59 including the NULL, while fgets() returns a string of specified
60 maximum length _including_ the NULL.*/
61 if (fgets(inBuf, strlen(outBuf1) - offset + 1, fp) != inBuf)
62 {
63 Fail("Error reading from file using fgets.\n");
64 }
65
66
67 expectedLen = strlen(outBuf1) - offset;
68 actualLen = strlen(inBuf);
69
70 if (actualLen < expectedLen)
71 {
72 Fail("fgets() was asked to read a one-line string and given the "
73 "length of the string as a parameter. The string it has "
74 "read is too short.\n");
75 }
76 if (actualLen > expectedLen)
77 {
78 Fail("fgets() was asked to read a one-line string and given the "
79 "length of the string as a parameter. The string it has "
80 "read is too long.\n");
81 }
82 if (memcmp(inBuf, outBuf1, actualLen) != 0)
83 {
84 /*We didn't read back exactly outBuf1*/
85 Fail("fgets() was asked to read a one-line string, and given the "
86 "length of the string as an parameter. It has returned a "
87 "string of the correct length, but the contents are not "
88 "correct.\n");
89 }
90
91 if (fclose(fp) != 0)
92 {
93 Fail("Error closing file after using fgets().\n");
94 }
95
96
97 PAL_Terminate();
98 return PASS;
99
100}
101
102
103