Solved

Problem with arrays and files

Posted on 1998-09-11
5
168 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 20 total points
Comment Utility
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 84

Expert Comment

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

Expert Comment

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

Author Comment

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

Expert Comment

by:ozo
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
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…
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.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now