Solved

Open and write to text file using C

Posted on 2012-03-27
6
381 Views
Last Modified: 2012-03-29
Hi,
I'm in the process of learning C.   I'm wanting to call a couple functions from the main which will  open a text file and then write to the text file.   Do I need to declare the FILE* fpNumbs in the main and in both funtions or can I declare it globally?    Can I pass the return value from the open back to the calling function to verify that it's open?   I'm using Visual Studio 2010 and it seems that when I use the fopen() that it actually creates the text file in the project.... so my validation is not failing when I test.    My objective here is to write the number sequence/pyramid to the text file.   Here's sample of the code:

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


   /*DECLARATIONS*/

void pyramid(void);
int openTxt(int);
void Oddnumb(void);
void closeTxt(void);


int main (void)
{
      /*LOCAL DEFINITIONS*/
      FILE* fpNumbs;
            
      /*STATEMENTS*/
      
      fpNumbs = fopen("MyOutput.txt", "w");

      if (fpNumbs == NULL)
      {
                  printf("Error opening text file!!\n");
                  system("pause");
      }
      else
                  pyramid();

      system("pause");

      return 0;
}

/*~~~~~~~~~~~~~~~~~  pyramid Function ~~~~~~~~~~~~~~~
Run through 9 rows and 9 columns, each time de-incrementing
the column by one.   Display number pattern to user.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

void pyramid(void)
{
/* LOCAL DEFINITIONS */      
int row;
int col;
int counter;
FILE* pfNumbs;

/* STATEMENTS */

row=0;
col=0;
counter=9;

for(row=1;row<=9;row++)
{
for(col=1;col<=counter;col++)
      printf("%d ", col);
      fprintf(fpNumbs, ......)
      printf("\n");
{
counter=counter-1;
}
}

}/* counter loop*/


This code doesnt reflect my use of openTxt(int)... I've been trying multiple solutions to see what would work... trial and error.... this no workie either.   LOL   Thanks for the assist!!
0
Comment
Question by:mojeaux
  • 3
  • 2
6 Comments
 

Author Comment

by:mojeaux
ID: 37774942
I believe I found part of my issue... i needed to use \\ in the location ...  for example:
fp=fopen("c:\\test.txt", "r");  

I'm still working to resolve and would love to hear other solutions or comments.   Thanks!
0
 

Author Comment

by:mojeaux
ID: 37774955
Ok.. now that I'm able to detect the txt file and determine that it's open... how do I write to it from another function.... in the example below, I move the variable to a global position and it still didnt work....

void pyramid(void)
{
/* LOCAL DEFINITIONS */      
int row;
int col;
int counter;

/* STATEMENTS */

row=0;
col=0;
counter=9;

for(row=1;row<=9;row++)
{
for(col=1;col<=counter;col++)
      printf("%d ", col);
    fprintf(pfNumbs, "%d", col);
      fprintf(pfNumbs, "\n");
      printf("\n");
{
counter=counter-1;
}
}

}/* counter loop*/
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 37774986
In the second code that you posted, you have pfNumbs, but in the first you have fpNumbs? That could be your problem.

If done correctly, it should have worked with it as a global although that wouldn't be recomended. What you should do is leave the FILE* variable local in main, and "pass" it as argument to pyramid. So in main would look like...


.....
FILE* fpNumbs;
           
      /*STATEMENTS*/
     
      fpNumbs = fopen("MyOutput.txt", "w");

      if (fpNumbs == NULL)
      {
                  printf("Error opening text file!!\n");
                  system("pause");
      }
      else
                  pyramid(fpNumbs);
....


And in the function you would have...

void pyramid(FILE* fpNumbs)
{
   ....
   fprintf(fpNumbs, "Blah");
   ....
}
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 8

Expert Comment

by:eager
ID: 37779904
You want to define your file handle in one place, such as main or as a global.  If it is global, you can share it with all of the functions.  If you declare it in main,  you need to pass the same file handle to each subroutine.

When you open a file and assign the value returned by fopen to a file handle, the handle points to internal information needed to locate the file.  This is what you did in main(), assigning the file handle value to fpNumbs, a local variable in main().  

When you declare pfNumbs in pyramid(), it is a different variable from the one with the same name in main().  You don't initialize it, so it probably contains a random value.  It definitely doesn't contain the same value as the file handle in main().

You also want to be careful to only open the file in one place, rather than creating multiple file handles pointing to the same file.
0
 

Author Closing Comment

by:mojeaux
ID: 37781210
Thank you.   This has been most helpful.    I attempted to load a part II to the question yesterday but did not see it listed here.   Still having a couple issues but think they are due to permissions.   Will continue to press on and will post again if not resolved.   Many thanks for the assist.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 37781419
Not a problem, glad to help!
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

758 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

18 Experts available now in Live!

Get 1:1 Help Now