How to writefile in new line in WIN32 API - api

I'm trying to write data to file. However, I want to add new data in new line, but now I can't.
HANDLE hFile;
hFile = CreateFile(_T("HELLO.txt"), // file to open
GENERIC_WRITE, // open for writing
0, // share for writing
NULL, // default security
// CREATE_NEW, // existing file only
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
// Write to File
BOOL bErrorFlag = FALSE;
DWORD dwPtr = SetFilePointer( hFile, 0, NULL, FILE_END); //set pointer position to end file
LPWSTR data = _T("Data '\n'");
DWORD dwBytesToWrite = lstrlenW(data)*2;
DWORD a = 0;
bErrorFlag = WriteFile(
hFile, // open file handle
data, // start of data to write
dwBytesToWrite, // number of bytes to write
&dwPtr, // number of bytes that were written
NULL); // no overlapped structure

Windows uses a CR/LF combination to signify the end of line, you need to write "\r\n" if you want the line break to show up correctly in, e.g., Notepad.

Related

How can I read \x1a from a file? [duplicate]

I am attempting to write a bittorrent client. In order to parse the file etc. I need to read a torrent file into memory. I have noticed that fread is not reading the entire file into my buffer. After further investigation it appears that whenever the symbol shown below is encountered in the file, fread stops reading the file. Calling the feof function on the FILE* pointer returns 16 indicating that the end of file has been reached. This occurs no matter where the symbol is placed. Can somebody explain why this happens and any solutions that may work.
The symbol is highlighted below:
Here is the code that does the read operation:
char *read_file(const char *file, long long *len){
struct stat st;
char *ret = NULL;
FILE *fp;
//store the size/length of the file
if(stat(file, &st)){
return ret;
}
*len = st.st_size;
//open a stream to the specified file
fp = fopen(file, "r");
if(!fp){
return ret;
}
//allocate space in the buffer for the file
ret = (char*)malloc(*len);
if(!ret){
return NULL;
}
//Break down the call to fread into smaller chunks
//to account for a known bug which causes fread to
//behave strangely with large files
//Read the file into the buffer
//fread(ret, 1, *len, fp);
if(*len > 10000){
char *retTemp = NULL;
retTemp = ret;
int remaining = *len;
int read = 0, error = 0;
while(remaining > 1000){
read = fread(retTemp, 1, 1000, fp);
if(read < 1000){
error = feof(fp);
if(error != 0){
printf("Error: %d\n", error);
}
}
retTemp += 1000;
remaining -= 1000;
}
fread(retTemp, 1, remaining, fp);
} else {
fread(ret, 1, *len, fp);
}
//cleanup by closing the file stream
fclose(fp);
return ret;
}
Thank you for your time :)
Your question is oddly relevant as I recently ran into this problem in an application here at work last week!
The ASCII value of this character is decimal 26 (0x1A, \SUB, SUBSTITUTE). This is used to represent the CTRL+Z key sequence or an End-of-File marker.
Change your fopen mode ("In [Text] mode, CTRL+Z is interpreted as an end-of-file character on input.") to get around this on Windows:
fp = fopen(file, "rb"); /* b for 'binary', disables Text-mode translations */
You should open the file in binary mode. Some platforms, in text (default) mode, interpret some bytes as being physical end of file markers.
You're opening the file in text rather than raw/binary mode - the arrow is ASCII for EOF. Specify "rb" rather than just "r" for your fopen call.

Embedded coding for TI CC2652RB. How to receive a string of characters from uart and save them in sd card?

I am using a TI launchpad CC2652RB. I have to receive data from another microcontroller and store the incoming data into an SD card. I am able to receive data successfully but unable to write complete data into the file. Only the last set of received bytes get written to the file i.e. every time the new string received overwrites the previously written string into the file.I am attaching my code for reference. I think the problem is in usage of file pointer or buffer length.\
void *alarmThread(void *arg0)
{
mqd_t *mqdes = arg0;
int msg;
UInt32 sleepTickCount;
sleepTickCount = 100000 / Clock_tickPeriod;
SDFatFS_Handle sdfatfsHandle;
FILE *src;
SDFatFS_init();
add_device(fatfsPrefix, _MSA, ffcio_open, ffcio_close, ffcio_read,
ffcio_write, ffcio_lseek, ffcio_unlink, ffcio_rename);
clock_settime(CLOCK_REALTIME, &ts);
sdfatfsHandle = SDFatFS_open(CONFIG_SDFatFS_0, DRIVE_NUM);
while (mq_receive(*mqdes, (char *)&msg, sizeof(msg), NULL) != -1)
{
src = fopen(inputfile, "w+");
fseek(src,0,SEEK_END);
//fwrite(&input, 1, 1, src);
fwrite(textarray, 1, strlen(textarray), src);
fwrite(buf, 1, strlen(buf), src);
fflush(stdin);
fclose(src);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
Task_sleep(sleepTickCount);
}
SDFatFS_close(sdfatfsHandle);
return(0);
}

Using f_mount to read and write data to text file

In my Application I need to open, read and write data to a text file using the calls f_open, f_read, and f_write.
It is failing to open the .txt file
res = f_open(&f_header.file, file_path, FA_OPEN_EXISTING | FA_WRITE | FA__WRITTEN | FA_READ | FA_CREATE_NEW );
printf("res value after f open %d \n\r",res);
if (res != FR_OK) {
printf("Failed to open %s, error %d\n\r", file_path, res);
}
This is giving error:
FR_NOT_ENABLED, /* (12) The volume has no work area */
For solving this error application program needs to perform f_mount function after each media change to force cleared the filesystem object.
How to use f_mount() call in this application to solve this issue?
I'm not clear about the 2nd parameter.
I added this f_mount(&fs0, "0://", 1); to solve this issue.
Before the f_open call. It is not taking f_mount() call also.
res=f_mount(&fs0,"0://", 1);
res = f_open(&f_header.file, file_path, FA_OPEN_EXISTING | FA_WRITE | FA__WRITTEN | FA_READ | FA_CREATE_NEW );
The code is stopping while run time before the f_mount()
Here is the source code for f_mount which I'm using:
FRESULT f_mount (
FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
const TCHAR* path, /* Logical drive number to be mounted/unmounted */
BYTE opt /* 0:Do not mount (delayed mount), 1:Mount immediately */
)
{
FATFS *cfs;
int vol;
FRESULT res;
const TCHAR *rp = path;
vol = get_ldnumber(&rp);
if (vol < 0) return FR_INVALID_DRIVE;
cfs = FatFs[vol]; /* Pointer to fs object */
if (cfs) {
#if _FS_LOCK
clear_lock(cfs);
#endif
#if _FS_REENTRANT /* Discard sync object of the current volume */
if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
#endif
cfs->fs_type = 0; /* Clear old fs object */
}
if (fs) {
fs->fs_type = 0; /* Clear new fs object */
#if _FS_REENTRANT /* Create sync object for the new volume */
if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
#endif
}
FatFs[vol] = fs; /* Register new fs object */
if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
res = find_volume(&fs, &path, 0); /* Force mounted the volume */
LEAVE_FF(fs, res);
}
The code is not showing any error/warnings at the time of make file.
I'm sure there is no problem with the code.
There is nothing wrong with the code.
Is this some problem related to the memory allocation or out of memory in emmc. What are the possible reason for this behaviour.
According to http://elm-chan.org/fsw/ff/doc/mount.html:
FRESULT f_mount (
FATFS* fs, /* [IN] Filesystem object */
const TCHAR* path, /* [IN] Logical drive number */
BYTE opt /* [IN] Initialization option */
);
Parameters
fs
Pointer to the filesystem object to be registered and cleared. Null pointer unregisters the registered filesystem object.
path
Pointer to the null-terminated string that specifies the logical drive. The string without drive number means the default drive.
opt
Mounting option. 0: Do not mount now (to be mounted on the first access to the volume), 1: Force mounted the volume to check if it is ready to work.
In other words, the second parameter is how you want to refer to this particular filesystem when later working with it.
For example, mounting it like so:
f_mount(&fs0, "0://", 1);
you would then be able to open files like this:
f_open(fp, "0://path/to/file", FA_CREATE_ALWAYS);

createprocess parent child, no information from child

I run MSDN example for createprocess parent and child but it doesn't work correctly,
becouse it writes the information to child input (what I've checked by printing it to the cmd), but after
printf( "\n->Contents of child process STDOUT:\n\n");
when it calls
ReadFromPipe();
in the cmd from which the application was called I receive nothing but it waits, waits. and only if I do ctrl+c it ends.
what might be the reason?
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#include <iostream> //only for cout
#define BUFSIZE 4096
HANDLE g_hChildStd_IN_Rd = NULL;
HANDLE g_hChildStd_IN_Wr = NULL;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hInputFile = NULL;
void CreateChildProcess(void);
void WriteToPipe(void);
void ReadFromPipe(void);
void ErrorExit(PTSTR);
int _tmain(int argc, TCHAR *argv[])
{
SECURITY_ATTRIBUTES saAttr;
printf("\n->Start of parent execution.\n");
// Set the bInheritHandle flag so pipe handles are inherited.
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
ErrorExit(TEXT("StdoutRd CreatePipe"));
// Ensure the read handle to the pipe for STDOUT is not inherited.
if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdout SetHandleInformation"));
// Create a pipe for the child process's STDIN.
if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
ErrorExit(TEXT("Stdin CreatePipe"));
// Ensure the write handle to the pipe for STDIN is not inherited.
if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
ErrorExit(TEXT("Stdin SetHandleInformation"));
// Create the child process.
CreateChildProcess();
// Get a handle to an input file for the parent.
// This example assumes a plain text file and uses string output to verify data flow.
if (argc == 1)
ErrorExit(TEXT("Please specify an input file.\n"));
g_hInputFile = CreateFile(
argv[1],
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if ( g_hInputFile == INVALID_HANDLE_VALUE )
ErrorExit(TEXT("CreateFile"));
// Write to the pipe that is the standard input for a child process.
// Data is written to the pipe's buffers, so it is not necessary to wait
// until the child process is running before writing data.
WriteToPipe();
printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]);
// Read from pipe that is the standard output for child process.
printf( "\n->Contents of child process STDOUT:\n\n");
ReadFromPipe();
printf("\n->End of parent execution.\n");
// The remaining open handles are cleaned up when this process terminates.
// To avoid resource leaks in a larger application, close handles explicitly.
return 0;
}
void CreateChildProcess()
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
TCHAR szCmdline[]=TEXT("C:\\Windows\\notepad.exe");//TEXT("C:\\Windows\\System32\\cmd.exe");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
std::cout<<"\nCreateChildProcess.\n";
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
siStartInfo.hStdInput = g_hChildStd_IN_Rd;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
// Create the child process.
bSuccess = CreateProcess(NULL,
szCmdline, // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if ( ! bSuccess )
ErrorExit(TEXT("CreateProcess"));
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
}
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if ( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if ( ! bSuccess ) break;
}
std::cout<<"\nchBuf: "<<chBuf<<std::endl;
// Close the pipe handle so the child process stops reading.
if ( ! CloseHandle(g_hChildStd_IN_Wr) )
ErrorExit(TEXT("StdInWr CloseHandle"));
}
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, 4, &dwRead, NULL);
std::cout<<"\nchBuf: "<<chBuf<<std::endl;
/*for (int i=0;i<2;i++) //read twice
{
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead == 0 ) break;
std::cout<<"\nchBuf: "<<chBuf<<std::endl;
bSuccess = WriteFile(hParentStdOut, chBuf,
dwRead, &dwWritten, NULL);
if (! bSuccess ) break;
} */
}
void ErrorExit(PTSTR lpszFunction)
// Format a readable error message, display a message box,
// and exit from the application.
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(1);
}
The reason is that you are starting a GUI application, notepad.exe, which will never write to stdout. So stdout is sitting open and has nothing written to it so the call to ReadFile blocks waiting for something to show up. Switch back to cmd.exe which you have commented out and you'll get output when from your ReadFromPipe call.
Also your ReadFromPipe function is just going to mostly output junk. To test it I changed it to:
void ReadFromPipe(void)
// Read output from the child process's pipe for STDOUT
// and write to the parent process's pipe for STDOUT.
// Stop when there is no more data.
{
DWORD dwRead;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = TRUE;
do
{
dwRead = 0;
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE-1, &dwRead, NULL);
chBuf[dwRead] = '\0';
std::cout<<"\nchBuf: "<<chBuf<<std::endl;
} while (bSuccess && dwRead > 0);
}

Can pipeline be used in sharing Dll in different process?

Before I get into to my question,let me explain what I am exactly doing.I have a main Process say ProcessA,I have hooked ProcessA and also injected dll(say myDll.dll) into the process space of ProcessA.Now at one point ProcessA kicks on another process which is ProcessB.Both the process A and B are in totally different Process memory space.I want to share the myDll.dll(which is inserted in processA sapce) in ProcessB(actually ProcessB's processSpace).Can it be done using pipe line method or any other suitable method.
thanks in advance.
The code of DLL will be automatically shared by different processes. For optimization only you should choose a good base address of the DLL (see http://msdn.microsoft.com/en-US/library/f7f5138s.aspx).
To share data between processes you can for example use Shared Memory objects or just place some variables which you need to share to a section which you mark as shared (see http://support.microsoft.com/kb/100634 and http://msdn.microsoft.com/en-us/library/h90dkhs0.aspx for details). To mark section ".SHAREDSECTIONNAME" as shared you can use
#pragma comment(linker, "/section:.SHAREDSECTIONNAME,RWS")
To have no conflicts in writing/reading from the shared memory you should use a named Event or Mutex exactly like in all other cases of multiprocess communication.
UPDATED based on the comment: If you create the child process yourself you receive the handle to the child process with full rights. So you have enough rights to make DLL infection with respect of CreateRemoteThread API. Here is a working code in C which start CMD.EXE and inject a MyTest.dll in the address space:
#include <Windows.h>
int main()
{
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi = {0};
TCHAR szCommandLine[4096] = TEXT("CMD.EXE");
BOOL bIsSuccess;
DWORD dwStatus;
LPCTSTR pszLibFile = TEXT("C:\\Oleg\\MyTest\\Release\\MyTest.dll");
PTSTR pszLibFileRemote = NULL;
HANDLE hThread = NULL;
int cb;
HMODULE hModule = NULL;
bIsSuccess = CreateProcess (NULL, szCommandLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
// Calculate the number of bytes needed for the DLL's pathname
cb = (1 + lstrlen(pszLibFile)) * sizeof(TCHAR);
__try {
PTHREAD_START_ROUTINE pfnThreadRtn;
// Allocate space in the remote process for the pathname
pszLibFileRemote = (PTSTR) VirtualAllocEx (pi.hProcess, NULL, cb, MEM_COMMIT, PAGE_READWRITE);
if (pszLibFileRemote == NULL) __leave; // error
// Copy the DLL's pathname to the remote process's address space
if (!WriteProcessMemory (pi.hProcess, pszLibFileRemote, (PVOID) pszLibFile, cb, NULL)) __leave;
// Get the real address of LoadLibraryW in Kernel32.dll
// Real address of Kernel32.dll in dwProcessId and in our Process MUST be the same !!!
// Remote Process MUST have Kernel32.dll loaded (SMSSS.EXE and System havn't)!!!
#ifdef UNICODE
pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress (GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW");
#else
pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress (GetModuleHandle(TEXT("Kernel32")), "LoadLibraryA");
#endif
if (pfnThreadRtn == NULL) __leave;
// Create a remote thread that calls LoadLibraryW(DLLPathname)
hThread = CreateRemoteThread (pi.hProcess, NULL, 0, pfnThreadRtn, (LPVOID)pszLibFileRemote, 0, NULL);
if (hThread == NULL) __leave;
dwStatus = ResumeThread (pi.hThread);
// Wait for the remote thread to terminate
if (WaitForSingleObject (hThread, INFINITE) != WAIT_OBJECT_0) __leave;
GetExitCodeThread (hThread, (PDWORD)&hModule);
// hModule is the address in the destination process (CMD.EXE)
// of the injected DLL
// You can verify that it is really loaded for example with respect of
// Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx)
}
__finally {
// Free the remote memory that contained the DLL's pathname
if (pszLibFileRemote != NULL)
bIsSuccess = VirtualFreeEx (pi.hProcess, pszLibFileRemote, 0, MEM_RELEASE);
if (hThread != NULL)
bIsSuccess = CloseHandle (hThread);
if (pi.hProcess != NULL)
bIsSuccess = CloseHandle (pi.hProcess);
if (pi.hThread != NULL)
bIsSuccess = CloseHandle (pi.hThread);
}
return 0;
}