Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
How,and what libs I need to create and manipulate a FILE in the Desktop? using only C, not C# or C++.
I'm using Codeblocks, I using allegro, what means I can´t use windows.h lib, The program need to work in windows.
In Windows Vista or higher, use SHGetKnownFolderPath to find he path for desktop. You have to use Unicode functions to get the file path, use _wfopen_s. You can write ANSI to the file, but it is recommended to write UTF16 or to convert text to UTF8.
#include <stdio.h>
#include <Windows.h>
#include <Shlobj.h>
int main()
{
wchar_t *desktop;
if(S_OK == SHGetKnownFolderPath(&FOLDERID_Desktop, 0, NULL, &desktop))
{
wprintf(L"Desktop path: %s\n", desktop);
wchar_t filename[MAX_PATH];
swprintf_s(filename, MAX_PATH, L"%s\\%s", desktop, L"file.txt");
wprintf(L"Filename path: %s\n", filename);
FILE *fp;
_wfopen_s(&fp, filename, L"w");
if(fp)
{
fprintf(fp, "Hello world\n");
fclose(fp);
}
else
{
wprintf(L"can't create file\n");
}
CoTaskMemFree(desktop);
}
return 0;
}
In Windows XP use SHGetSpecialFolderPath (deprecated)
#include <stdio.h>
#include <Windows.h>
#include <Shlobj.h>
int main()
{
wchar_t desktop[MAX_PATH];
if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_DESKTOP | CSIDL_FLAG_CREATE, NULL, 0, desktop)))
{
wprintf(L"desktop: %s\n", desktop);
wchar_t path[MAX_PATH];
swprintf(path, L"%s\\%s", desktop, L"filename.txt");
HANDLE handle = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(handle != INVALID_HANDLE_VALUE)
{
DWORD temp;
const char *buf = "hello world";
WriteFile(handle, buf, strlen(buf), &temp, NULL);
CloseHandle(handle);
}
else
{
printf("can't create file\n");
}
}
return 0;
}
Given that you are on Windows, you'd want to look at CreateFile and its associated functions.
The lifecycle of a file is as follows: You can create it (or, if it exists, open it) using CreateFile, and once it is created/opened, you can use the resulting file handle to manipulate it with ReadFile, WriteFile, and potentially DeleteFile. Once you're done, you need to close the handle with CloseHandle.
1 If you are using Unix or Unix-like system, you can call
system("touch ~/Desktop/FILE");
in your code, and you need to #include <stdlib.h>.
This calls the command "touch ~/Desktop/FILE". If you want to handle (read/write) the file after this, you have to call fopen with correct mode. But the 2nd method is much better if you want to write something into the file.
2 You can also use
For Unix or Unix-like operating systems:
FILE *file = fopen("~/Desktop/FILE", "w+")
For Windows:
FILE *file = fopen("C:\\Users\\YOUR_USER_NAME\\Desktop\\FILE", "w+")
(*Assumes you are using the default user folder location.)
This creates the file, and then you can read/write to the file after this. Be sure to used the correct mode. Here is a reference for fopen and modes. Remember to #include <stdlib.h>.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to print Malayalam (a south Indian Language) as c/c++ program output but it shows some unfamiliar characters both in terminal and in user interface using WINAPI.
(The file "malayalam.txt" contain some Malayalam words.)
#include <stdio.h>
#include <windows.h>
main() {
char s[100];
FILE *fp;
fp = fopen("malayalam.txt", "r");
if (fp == NULL) {
puts("Cannot open file");
}
while (fgets(s, 100, fp) != NULL) {
printf("%s", s);
MessageBox(NULL, s, "Malayalam", MB_OK);
}
fclose(fp);
}
The example from the following link may help you fix this issue for WINAPI.
You need to find the unicode equivalent of your Malayalam word in the .txt file you can convert it from here http://www.aksharangal.com
An example from the following page http://harikrishnanvs.blogspot.in/2011/12/printing-malayalam-as-c-program-output.html
WIN32 program to print my name in Malayalam -MessageBox
This works for windows 7, but not working in XP
Create new project in visual studio 2010.
File-->New-->Project-->Win32 Project
Name the project
click OK
Finish
include header files stdafx.h, tchar.h.
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance, PSTR szCommandline,int iCmdshow)
{
TCHAR c[4];
c[0]=3385;
c[1]=3376;
c[2]=3391;
c[3]='\0';
TCHAR szbuffer[100];
_stprintf(szbuffer,_T("%ls"),c);
MessageBox(NULL,szbuffer,TEXT("HELLO ALL"),0);
return 0;
}
Please ensure that , Configuration Properties--->Character set---> Use Unicode Character Set option is selected.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Getting Filename from file descriptor in C
Is there a simple and (reasonably) portable way of getting the filename from a FILE*?
I open a file using f = fopen(filename, ...) and then pass down f to various other functions, some of which may report an error. I'd like to report the filename in the error message but avoid having to pass around the extra parameter.
I could create a custom wrapper struct { FILE *f, const char *name }, but is there perhaps a simpler way? (If the FILE* wasn't opened using fopen I don't care about the result.)
On some platforms (such as Linux), you may be able to fetch it by reading the link of /proc/self/fd/<number>, as so:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
char path[1024];
char result[1024];
/* Open a file, get the file descriptor. */
FILE *f = fopen("/etc/passwd", "r");
int fd = fileno(f);
/* Read out the link to our file descriptor. */
sprintf(path, "/proc/self/fd/%d", fd);
memset(result, 0, sizeof(result));
readlink(path, result, sizeof(result)-1);
/* Print the result. */
printf("%s\n", result);
}
This will, on my system, print out /etc/passwd, as desired.
It's a bit difficult, because a FILE* can read/write from a file handle which isn't associated with a named file at all (for example an unnamed pipe or a socket). You can obtain the file handle with fileno() and then there are system specific ways to learn about the file name. Here's a discussion on how to do this under Linux:
Getting Filename from file descriptor in C
and under Windows this isn't much easier either:
http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx (as an extra step here, you use _get_osfhandle() to get the Windows file handle from the c-library file descriptor)
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Getting Filename from file descriptor in C
Is there a simple and (reasonably) portable way of getting the filename from a FILE*?
I open a file using f = fopen(filename, ...) and then pass down f to various other functions, some of which may report an error. I'd like to report the filename in the error message but avoid having to pass around the extra parameter.
I could create a custom wrapper struct { FILE *f, const char *name }, but is there perhaps a simpler way? (If the FILE* wasn't opened using fopen I don't care about the result.)
On some platforms (such as Linux), you may be able to fetch it by reading the link of /proc/self/fd/<number>, as so:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
char path[1024];
char result[1024];
/* Open a file, get the file descriptor. */
FILE *f = fopen("/etc/passwd", "r");
int fd = fileno(f);
/* Read out the link to our file descriptor. */
sprintf(path, "/proc/self/fd/%d", fd);
memset(result, 0, sizeof(result));
readlink(path, result, sizeof(result)-1);
/* Print the result. */
printf("%s\n", result);
}
This will, on my system, print out /etc/passwd, as desired.
It's a bit difficult, because a FILE* can read/write from a file handle which isn't associated with a named file at all (for example an unnamed pipe or a socket). You can obtain the file handle with fileno() and then there are system specific ways to learn about the file name. Here's a discussion on how to do this under Linux:
Getting Filename from file descriptor in C
and under Windows this isn't much easier either:
http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx (as an extra step here, you use _get_osfhandle() to get the Windows file handle from the c-library file descriptor)
here's another question about splice(). I'm hoping to use it to copy files, and am trying to use two splice calls joined by a pipe like the example on splice's Wikipedia page. I wrote a simple test case which only tries to read the first 32K bytes from one file and write them to another:
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, char **argv) {
int pipefd[2];
int result;
FILE *in_file;
FILE *out_file;
result = pipe(pipefd);
in_file = fopen(argv[1], "rb");
out_file = fopen(argv[2], "wb");
result = splice(fileno(in_file), 0, pipefd[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
printf("%d\n", result);
result = splice(pipefd[0], NULL, fileno(out_file), 0, 32768, SPLICE_F_MORE | SPLICE_F_MOVE);
printf("%d\n", result);
if (result == -1)
printf("%d - %s\n", errno, strerror(errno));
close(pipefd[0]);
close(pipefd[1]);
fclose(in_file);
fclose(out_file);
return 0;
}
When I run this, the input file seems to be read properly, but the second splice call fails with EINVAL. Anybody know what I'm doing wrong here?
Thanks!
From the splice manpage:
EINVAL Target file system doesn't support splicing; target file is
opened in append mode; neither of the descriptors refers to a
pipe; or offset given for non-seekable device.
We know one of the descriptors is a pipe, and the file's not open in append mode. We also know no offset is given (0 is equivalent to NULL - did you mean to pass in a pointer to a zero offset?), so that's not the problem. Therefore, the filesystem you're using doesn't support splicing to files.
What kind of file system(s) are you copying to/from?
Your example runs on my system when both files are on ext3 but fails when I use an external drive (I forget offhand if it is DOS or NTFS). My guess is that one or both of your files are on a file system that splice does not support.
The splice(2) system call is for copying between files and pipes and not between files, so it can not be used to copy between files, as has been pointed out by the other answers.
As of Linux 4.5 however a new copy_file_range(2) system call is available that can copy between files. In the case of NFS it can even cause server side copying.
The linked man page contains a full example program.
If I have a buffer which contains the data of a file, how can I get a file descriptor from it?
This is a question derived from how to untar file in memory
I wrote a simple example how to make filedescriptor to a memory area:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
char buff[]="qwer\nasdf\n";
int main(){
int p[2]; pipe(p);
if( !fork() ){
for( int buffsize=strlen(buff), len=0; buffsize>len; )
len+=write( p[1], buff+len, buffsize-len );
return 0;
}
close(p[1]);
FILE *f = fdopen( p[0], "r" );
char buff[100];
while( fgets(buff,100,f) ){
printf("from child: '%s'\n", buff );
}
puts("");
}
Not possible in plain C. In plain C all file access happens via FILE * handles and these can only be created with fopen() and freopen() and in both cases must refer to a file path. As C tries to be as portable as possible, it limits I/O to the absolute bare minimum that probably all systems can support in some way.
If you have POSIX API available (e.g. Linux, macOS, iOS, FreeBSD, most other UNIX systems), you can use fmemopen():
char dataInMemory[] = "This is some data in memory";
FILE * fileDescriptor = fmemopen(dataInMemory, sizeof(dataInMemory), "r");
This is a true file handle that can be used with all C file API. It should also allow seeking, something not possible if you work with pipes as pipes support no seeking (you can emulate forward seeking but there is no way to ever seek backwards).
You can't. Unlike C++, the C model of file I/O isn't open to extension.