Solved

Open and write to text file using C

Posted on 2012-03-27
6
396 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
pre4 challenge 19 100
zeroFront challenge 7 96
java constructor error 8 118
java continue statement 10 137
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

805 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