-
varied file reading
i need t read and write to files. but the problem is there are several of them, and they vary according to numbers..
for example, i need to read from r1t001, r1t002...and so on, and write to files with similar names... the second number in the file names have a buffer zeros...
i know i need variables which can change in loops, but how do i implement this in filenames and also have the buffer of zeros in the case of single, and tens of numbers..
thanks in advance!
-
The real question is how do you do this in char arrays; C's version of strings.
Filenames are nothing special, just plain old strings.
Look at functions such as sprintf(), strcat() etc.
-
thanks for that! sprintf worked..
tho sprintf attaches a '\0' to the end of the string, but i will have to delete that wouldnt i?otherwise the file operators cant handle the null character right?
-
Correct.
Code:
if ((filename[strlen(filename)-1])=='\n')
filename[strlen(filename)-1])=='\0;'
Will do what you want.
This is a function that prints out data into numbered files. It's a bit different from your format, but you'll get the idea, I believe:
Code:
void printIt(long i, long j) {
char fname[20];
long k;
FILE *fpout;
ltoa(i, fname, 10); //makes a long int, into a string
strcat(fname, ".txt"); //adds the file extension I want
printf("\nFilename: %s", fname); //just a √
if((fpout=fopen(fname, "w"))==NULL) {
printf("\n Error opening level 0 output file - terminating");
exit(1);
}
for(k=0;k<j;k++) //prints out a small struct, you can ignore this part
fprintf(fpout, "%s %s %d\n", recs[k].id, recs[k].doc, recs[k].bill);
fclose(fpout);
}
-
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
int p,t;
t = 1;
p = 1;
char filename[12];
for(n=0;n<12;n++)
{
sprintf(filename,"p%dt%03d.state",p,t);
printf("\n result:%s",filename);
t = t + 1;
n++;
}
return 0;
}
thats part of some pleriminary code i wrote...but the weird thing is, the sprintf statement seems to be resetting the "n" variable to 0, and it results in the program going into an endless loop...
and when i build, there are n errors or warnings..
what am i doing wrong?
-
sprintf() doesn't include the newline char in the string it writes.
Just for fun, try making filename bigger. Sounds like you're going out of bounds a bit.
Post your output to your code.
-
thanks for that! yeah...the filename was too small.thanks for that!