?
Solved

Problem with arrays and files

Posted on 1998-09-11
5
Medium Priority
?
178 Views
Last Modified: 2010-04-15
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
Comment
Question by:SHAHZAD
  • 2
  • 2
5 Comments
 
LVL 4

Accepted Solution

by:
sganta earned 60 total points
ID: 1252646
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
 
LVL 85

Expert Comment

by:ozo
ID: 1252647
  char msg[] = {'1','2','3','4','5','6','7','\0'};
or
   char msg[] = "1234567";
0
 
LVL 4

Expert Comment

by:sganta
ID: 1252648
Yes, ozo is right !
Thank you ozo for correcting my mistake.
0
 

Author Comment

by:SHAHZAD
ID: 1252649
what if the array comes from other part of the program and is very large(100x100).How would i handle that.
0
 
LVL 85

Expert Comment

by:ozo
ID: 1252650
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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question