I have this simple program that counts characters in a line as well as a specific character z and Z. I am trying to figure out the simplest way to output my results to a file "outfile.txt". any ideas?


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{

char string[80];
char *s;
int count=0;
int len;
int zcount=0;

}

printf("Enter string: ");
gets(string);
len=strlen(string);
printf("The length of your sentence is %d characters long\n",len);

for(s = string; *s != '\0'; s++)
{
if((*s == 'z') || (*s == 'Z'))
zcount++;
}

printf("Number of z's in your sentence are %d",zcount);

getchar();

return(0);
}

I have this simple program that counts characters in a line as well as a specific character z and Z. I am trying to figure out the simplest way to output my results to a file "outfile.txt". any ideas?

Without modifying your code too much, this could be a solution.

/* for psuspect at Daniweb
 * outfile_txt.c
 */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
    FILE *file_handler;
    char string[80];
    char *s;
    int count=0;
    int len;
    int zcount=0;


    printf("Enter string: ");
    gets(string);
    len=strlen(string);
    printf("The length of your sentence is %d characters long\n",len);
    
   /* open a file to disk for writting and check that it can be done */
    file_handler = fopen("C:\\outfile.txt", "w");
    if(file_handler == NULL)
    {
        fprintf(stderr, "Could not open %s - %s\n", "C:\\outfile.txt", sys_errlist[errno]);
        exit(1);
    }

    for(s = string; *s != '\0'; s++)
    {
        if((*s == 'z') || (*s == 'Z'))
            zcount++;
    }
    
   /* Write to file and return error if it can't be done */
    if(fprintf(file_handler, "The length of your sentence is %d characters long\n\n",len) < 0)
    {
        perror("Could not write to the file");
        fclose(file_handler);
        exit(1);
    }
  
  /* write to file */
    fprintf(file_handler,"Number of z's in your sentence are %d",zcount);
  
 /* close file at  ending */ 
    fclose(file_handler);

    printf("Number of z's in your sentence are %d",zcount);

    getchar();

    return(0);
}

Now I want to point out that using the function gets is considerate bad practice since it can produce buffer over-runs.

Also there's a extra } closing the main function before the first printf
request.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.