Here's my task and below you can find my specific question and the code I wrote:
Write a program that reads strings and writes them to a file. The string must be dynamically allocated and the string can be of arbitrary length. When the string has been read it is written to the file. The length of the string must be written first then a colon (‘:’) and then the string. The program stops when user enters a single dot (‘.’) on the line.
For example:
User enters: This is a test
Program writes to file: 14:This is a test
Question:
My code adds the number of characters and the colon, but not the string I typed, and when entered "." it wont exit
This is the code I have so far:
#pragma warning(disable: 4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main() {
char key[] = ".";
char *text;
int i;
text = (char*)malloc(MAX_NAME_SZ);
FILE* fp;
do {
printf("Enter text or '.' to exit: ", text);
fgets(text, MAX_NAME_SZ, stdin);
for (i = 0; text[i] != '\0'; ++i);
printf("%d: %s", i);
fp = fopen("EX13.txt", "w");
while ((text = getchar()) != EOF) {
putc(text, fp);
}
fclose(fp);
printf("%s\n", text);
} while (strncmp(key, text, 1) != 0);
puts("Exit program");
free(text);
return 0;
}
I think this should work for strings that are shorter than 255 chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SZ 256
int main()
{
char key[] = ".\n";
char *text;
text = (char*)malloc(MAX_NAME_SZ);
if (text == NULL)
{
perror("problem with allocating memory with malloc for *text");
return 1;
}
FILE *fp;
fp = fopen("EX13.txt", "w");
if (fp == NULL)
{
perror("EX13.txt not opened.\n");
return 1;
}
printf("Enter text or '.' to exit: ");
while (fgets(text, MAX_NAME_SZ, stdin) && strcmp(key, text))
{
fprintf(fp, "%ld: %s", strlen(text) - 1, text);
printf("Enter text or '.' to exit: ");
}
free((void *) text);
fclose(fp);
puts("Exit program");
return 0;
}