我尝试将用户输入写入文件,以便可以通过wifi发送。我已经关注了一些教程,从我收集的内容来看,这似乎是将数据写入文件的合适方法。不幸的是,虽然程序可以识别我想要写的信息,但它不会将其写入文件,甚至不会自己创建文件。
#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
}
输出:
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
我还是很新,所以任何反馈都会非常感激。同样,如果任何人对OSX的Multipeer连接框架有一个模糊的理解,并且可以将我引导到一个资源,那就太棒了。