Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 180
  • Last Modified:

Problem with arrays and files

When I executes the program given below,and check the contents of the file to which the contents of array are supposed to be written,there garbage is stored,instead of the array contents.Can anybody tell me what is the problem?
 
#include <stdio.h>

int main(void)
{
   FILE *in;
   char msg[] = {1,2,3,4,5,6,7};
   int i = 0;
   in=fopen("file","w");
   while (msg[i])
      putc(msg[i++],in);
   fclose(in);
   return 0;
}
0
SHAHZAD
Asked:
SHAHZAD
  • 2
  • 2
1 Solution
 
sgantaCommented:
Hi !

It should be like this
#include <stdio.h>

    int main(void)
    {
       FILE *in;
       char msg[] = {'1','2','3','4','5','6','7'};
       int i = 0;
       in=fopen("file","w");
       while (msg[i])
          putc(msg[i++],in);
       fclose(in);
       return 0;
    }
0
 
ozoCommented:
  char msg[] = {'1','2','3','4','5','6','7','\0'};
or
   char msg[] = "1234567";
0
 
sgantaCommented:
Yes, ozo is right !
Thank you ozo for correcting my mistake.
0
 
SHAHZADAuthor Commented:
what if the array comes from other part of the program and is very large(100x100).How would i handle that.
0
 
ozoCommented:
That may depend what you're getting from the other part of the program, and what you want to do with it, but perhaps you'd want

  putc('0'+msg[i++],in);

or

  fprintf(in,"%d,",msg[i++])'
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now