Create a file: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|C}}: +Windows)
Line 539: Line 539:


=={{header|C}}==
=={{header|C}}==
=== ISO C ===
ISO C (directory creation not supported):
ISO C (directory creation not supported):
<lang c>#include <stdio.h>
<lang c>#include <stdio.h>
Line 549: Line 550:
}</lang>
}</lang>


POSIX:
=== POSIX ===


{{works with|POSIX}}
{{works with|POSIX}}
Line 568: Line 569:


(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")
(for creation in the filesystem root, replace the filenames by "/output.txt" and "/docs")

=== Windows API ===

First, a solution with the C runtime functions <code>_creat</code> and <code>_mkdir</code>.

<lang c>#include <direct.h>
#include <io.h>
#include <sys/stat.h>

int main(void) {
int f;
f = _creat("output.txt", _S_IWRITE);
if (f == -1) {
perror("Unable to create file");
} else {
_close(f);
}
if (_mkdir("docs") == -1) {
perror("Unable to create directory");
}
f = _creat("\\output.txt", _S_IWRITE);
if (f == -1) {
perror("Unable to create file");
} else {
_close(f);
}
if (_mkdir("\\docs") == -1) {
perror("Unable to create directory");
}

return 0;
}</lang>

Another solution with the kernel32 API functions <code>CreateFile</code> and <code>CreateDirectory</code>.

<lang c>#include <windows.h>
#include <stdio.h>

int main(void) {
HANDLE hFile;
hFile = CreateFile("output.txt", GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Unable to create file\n");
} else {
CloseHandle(hFile);
}
if (CreateDirectory("docs", NULL) == 0) {
printf("Unable to create directory\n");
}

hFile = CreateFile("\\output.txt", GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Unable to create file\n");
} else {
CloseHandle(hFile);
}

if (CreateDirectory("\\docs", NULL) == 0) {
printf("Unable to create directory\n");
}

return 0;
}</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==