Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Experiment 9: File Access Using Sockets

Lesson 9 of 11 in the free Network Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Program Statement

A file-transfer pair: the client asks for a filename, the server streams it back. The read-loop handles short counts — Unit 1's readn/writen lesson in practice.

/* server fragment: send any requested file */
int n; char name[256], buf[4096];
n = read(cfd, name, sizeof(name)-1); name[strcspn(name, "\r\n")] = 0;
FILE *fp = fopen(name, "rb");
if (!fp) { write(cfd, "ERR no such file\n", 17); }
else {
    write(cfd, "OK\n", 3);
    while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
        writen(cfd, buf, n);                 /* loop until all sent */
    fclose(fp);
}
shutdown(cfd, SHUT_WR);                      /* half-close = EOF    */

/* client fragment */
write(fd, argv[2], strlen(argv[2])); write(fd, "\n", 1);
FILE *out = fopen("download.out", "wb");
while ((n = read(fd, buf, sizeof(buf))) > 0) fwrite(buf, 1, n, out);

Record Task

Verify with md5sum that the downloaded copy is byte-identical to the original.

Theory Link

Unit 2 "shutdown vs close" — the half-close (shutdown(fd, SHUT_WR)) is what signals end-of-file to the client cleanly while still allowing the server to read any remaining data.