c - Return an array of files -
i trying create function returns array of files couldn't find way access array outside of function. here's tried:
file* *arquivoescrita(int k) //gerar nome de arquivo { char filename[sizeof("file1000000000000.txt")]; static file* arquivos[2]; (int = k; < k+2; ++i) { sprintf(filename, "file%d.txt", i); arquivos[i] = fopen(filename,"r"); } return arquivos; }
and i'm calling function inside main this:
file* psaidas[2]; psaidas = arquivoescrita(0);
and error
error: array type 'file *[2]' not assignable psaidas = arquivoescrita(0);
how can access kind of array?
there 1 issue in returning file **
array of open file stream, need know how many open. have couple of choices, (1) pass pointer function , update pointer reflect number of files opened, or (2) makes more sense, pass file *
array parameter function , return number of files opened use index in calling function. (you check stream before attempting read it)
for example, if declared file pointer array file *fparray[maxf] = {null};
in main
, pass parameter filled in function. e.g.
nfiles = openmulti (fparray, 0, maxf);
your function take array, other type of array, , fill elements open and validated file *
elements:
int openmulti (file **fp, size_t k, size_t n) { char fname[maxfn] = ""; size_t i, idx = 0; (i = k; < n; i++) { sprintf (fname, "file%zu.txt", i); fp[idx] = fopen (fname, "r"); if (!fp[idx]) continue; idx++; } return (int)idx; }
(the beginning number file#.txt
passed k
, number of files open passed n
)
a short example opening file0.txt
, file1.txt
in function reading in calling function be:
#include <stdio.h> enum { maxf = 2, maxfn = 256 }; int openmulti (file **fp, size_t k, size_t n); int main (void) { file *fparray[maxf] = {null}; size_t i, nfiles; nfiles = openmulti (fparray, 0, maxf); /* populate array */ if (nfiles < maxf) /* validate number of open files */ fprintf (stderr, "warning: '%zu' of %d files open.\n", nfiles, maxf); (i = 0; < nfiles; i++) { /* read/output file contents */ printf ("\ncontents of 'farray[%zu]'\n\n", i); char buf[maxfn] = ""; while (fgets (buf, maxfn, fparray[i])) printf ("%s", buf); fclose (fparray[i]); /* close file after reading */ } return 0; } int openmulti (file **fp, size_t k, size_t n) { char fname[maxfn] = ""; size_t i, idx = 0; (i = k; < n; i++) { sprintf (fname, "file%zu.txt", i); fp[idx] = fopen (fname, "r"); if (!fp[idx]) continue; idx++; } return (int)idx; }
example input files
$ cat file0.txt 1. 2. hello -- file0.txt 3. $ cat file1.txt 1. 2. hello -- file1.txt 3.
example use/output
$ ./bin/filemultiopen contents of 'farray[0]' 1. 2. hello -- file0.txt 3. contents of 'farray[1]' 1. 2. hello -- file1.txt 3.
unless there critical need return file **
, seems make things bit more straight forward pass array function , return number of files opened. both ways possible, whatever fits needs.
let me know if have additional questions.
Comments
Post a Comment