A question about c

I know this forum is about C++ but I have a question about 'C'. I need to write a function to open a file (easy in c++) however I have no idea how to since I am using an array to store my file name. Anybody know of any good websites like this one that has a forum for 'C'?
I do believe there are actually a few people here who know C syntax as well, maybe one of them will swing by and help you out, we don't want to see you go :)
Last edited on
I like C++ way more!!! just need help with an assignment
This forum also answers C questions.

The C file operations work over a FILE* object.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>

int main()
  {
  FILE* fp;

  fp = fopen( "myfoo.txt", "rb" );
  if (fp == NULL)
    complain();

  fwhatever( fp, ... );

  fclose( fp );

http://cplusplus.com/reference/clibrary/cstdio/

Hope this helps.
I get how to open files and read and such.
My problem is creating a function outside main that opens the file then allows the rest of the program to manipulate the file. here is some pseudocode to help describe what I'm looking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define MAXSIZE 256;
main 
{
char fileName [MAXSIZE];
printf(" please enter the filename/path to open the file")
fgets(filename,MAXSIZE,256)
openfile () // this is what I want to create it will open the file
... rest of code here....
return 0;
}

void openFile ()
{ 
code to open a file goes here
}


I have 2 questions that are tricking me up about this. I have learned arrays cant be passed into strings. this is no good because from all I've learned the filename is stored as a character array.
so anytime I try to pass filename in openFile ()it says incompattible. I think using a pointer would fix this but I'm not sure and I am really uncomfortable (inexperienced and confused) using them.

secondly I have no Idea if C is different from CPP in signatures. I can get my program to partially work if I put the openfile function above main. however the program wont work if I put it under main. so I'm also curious where functions go in relation to main in C. the book I am using shows only with functions above main which I find completely backwards.

thanks to anyone in advance for helping and also those who have helped

This is just a scope issue. A file opened in main, will be local to main. Meaning no other function can access it directly. You're on the right track using pointers. You could also send the file name to a function that may need to open that file, but I don't think that would be nearly as efficient. And I'm also not sure if two different file streams can be attached to the same file. I don't mess with file I/O often
Topic archived. No new replies allowed.