?
Solved

Open and write to text file using C

Posted on 2012-03-27
6
Medium Priority
?
403 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 36

Accepted Solution

by:
mccarl earned 2000 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 36

Expert Comment

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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

777 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