I'm attempting to get user input to be written to a file so that it can be sent over wifi. I've followed some tutorials and from what I gather this seems to be the appropriate way to approach writing data to a file. Unfortunately it seems that, while the program can identify the information that I want written, it does not write it to a file nor even create the file itself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_STR_LEN 120
int main(){
char *cArray[MAX_STR_LEN] = { "example", "dinosaurs" };
char cInput[MAX_STR_LEN] = { 0 };
int y = 0;
FILE *pWrite;
printf("Type your message:\n");
fgets(cInput, MAX_STR_LEN, stdin);
cInput[strlen(cInput) - 1] = 0; /* strip newline from input */
printf("\nInitialised string array:\n");
while (cArray[y]){
char * ptr = cInput;
while ((ptr = strstr(ptr, cArray[y])) != NULL){
char *ep = strchr (ptr, ' ');
if (ep) *ep = 0; /* null-terminate at space */
printf("%s\n", ptr++);
pWrite = fopen("test.txt", "a");
if ( pWrite != NULL ) {
fprintf(pWrite, "%s\n", ptr++);
fclose(pWrite);
} else {
goto ErrorHandler; //there is a file i/o error
}
if (ep) *ep = ' '; /* put the space back */
}
y++;
}
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Timestamp: %s", asctime (timeinfo) );
exit(EXIT_SUCCESS); //exit program normally
ErrorHandler:
perror("The following error occurred");
exit(EXIT_FAILURE); //exit program with error
}
Output:
Type your message:
this is an example
Initialised string array:
example
Timestamp: Sat Mar 7 12:20:02 2015
Program ended with exit code: 0
I'm still very new at this so any and all feedback would be greatly appreciated. Similarly, if anyone has a vague understanding of the Multipeer Connectivity Framework for OSX and could direct me to a resource, that would be fantastic.
Aucun commentaire:
Enregistrer un commentaire