Kamis, Mei 15, 2008

Bhs C Dasar - Chapter VI

untuk bermain dengan file kita harus mendeklarasikannya terlebih dahulu;
contoh;

FILE *ptrfile ; //pointer penunjuk kesebuah file
ptrfile = fopen(outfilename, "w"); /// membuka suatu file ,ditampung disebuah ptrfile
fclose (outfilename); // menutup kembali file yang barusan dibuka

perhatikan tanda "w " , itu disebut dengan modus
modus sangat perlu jika kita bermain dengan file :
r ³ Open for reading only
w ³ Create for writing
³ If a file by that name already exists, it will be overwritten.
a ³ Append; open for writing at end of file, or create for
³ writing if the file does not exist.
r+ ³ Open an existing file for update (reading and writing)
w+ ³ Create a new file for update (reading and writing).
³ If a file by that name already exists, it will be overwritten.
a+ ³ Open for append; open for update at the end of the file, or
³ create if the file does not exist.


contoh :
#include
int main()
{
FILE *infile, *outfile, *printer;
char infilename[25], outfilename[25];
int c;
printf("Enter input file name ----> ");
scanf("%s", infilename);
infile = fopen(infilename, "r");

printf("Enter output file name ---> ");
scanf("%s", outfilename);
outfile = fopen(outfilename, "w");
printer = fopen("PRN", "w");
do
{
c = getc(infile);
if (c != EOF)
{
putchar(c);
putc(c, outfile);
putc(c, printer);
}
} while (c != EOF);
fclose(printer);
fclose(infile);
fclose(outfile);
return 0;
}
contoh lain :
#include
int main()
{
FILE *infile;
char *c, infilename[25], inputline[100];
int line = 1;

printf("Enter input file name ----> ");
scanf("%s", infilename);
infile = fopen(infilename, "r");

printf("%5d", line);
do
{
c=fgets(inputline, 100, infile); /* baca perbaris */
if (c != NULL)
{
printf("%5d %s", line, inputline);
line++;
}
} while (c != NULL);

fclose(infile);

return 0;
}

#include
int main()
{
FILE *fp1;
char oneword[100], filename[25];
char *c;

printf("Enter filename -> ");
scanf("%s", filename); /* baca nama file */
fp1 = fopen(filename, "r");
if (fp1 == NULL)
{
printf("File doesn't exist\n");
exit (1);
}
else
{
do
{
c = fgets(oneword, 100, fp1); /* baca perbaris dari file*/
if (c != NULL)
printf("%s", oneword); /* tampilkan dimonitor */
} while (c != NULL); /* ulangi sampai ketemu NULL
*/
}
fclose(fp1);

return 0;
}

Tidak ada komentar: