Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Application Programming › Copying contents of file in C
New Posts  All Forums:Forum Nav:

Copying contents of file in C

post #1 of 5
Thread Starter 
I am requesting and receiving from a web server. While I can output what I receive into stdout, I can't seem to put it into a file.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>


int main(int argc, char *argv[]) {
    
    int conn_s = socket(AF_INET, SOCK_STREAM, 0);
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;
    
    struct addrinfo *addr = (struct addrinfo *) calloc(1, sizeof(struct addrinfo));
    
    getaddrinfo("google.com", "80", &hints, &addr);
    
    connect(conn_s, addr->ai_addr, sizeof(struct sockaddr_in));
    
    char *http_request = "GET / HTTP/1.1\n\n";
    
    send(conn_s, http_request, strlen(http_request), 0);
    FILE *sockfile = (FILE *) fdopen(conn_s, "r");
    FILE *fp = fopen("/Users/leekaiwei/Desktop/results.txt", "w");
    int ch;
    
    while ((ch = fgetc(sockfile)) != EOF) {
        printf("%c", ch);
        fputc(ch, fp);
    }
    
    close(conn_s);
    free(addr);
    fclose(fp);
    fclose(sockfile);
    return 0;
}

Thanks.
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
post #2 of 5
As long as sockfile is fine then I can't see a problem because your file writer is fine.

ie this part of your program is fine,

FILE *sockfile = fopen("theFile.txt", "r");
FILE *fp = fopen("theCopy.txt", "w");
int ch;

while ((ch = fgetc(sockfile)) != EOF) {
printf("%c", ch);
fputc(ch, fp);
}

fclose(fp);
fclose(sockfile);
return 0;

Edit,..

Its what I originally thought.


change FILE *fp = fopen("/Users/leekaiwei/Desktop/results.txt", "w");

to FILE *fp = fopen("C:/Users/leekaiwei/Desktop/results.txt", "w"); im guessing that you are in windows... and it will output as expected. I think you would be best not using static paths.
Edited by andrewmchugh - 11/4/12 at 5:54pm
Andr3w's RiG
(16 items)
 
   
CPUMotherboardGraphicsRAM
Intel Core i7 920 @ 4.0 (HT off) ASUS P6TD Deluxe EVGA GTX 580 SC 6GB Corsair XMS3 1600 
Hard DriveCoolingCoolingCooling
2x RAID0 OCZ VERTEX2 SSD 60GB EK FC580GTX EK Supreme HF Laing D5 
OSMonitorKeyboardPower
Windows 7 64 bit / Fedora 16 / Mint 13 DELL S2209W Ducky 9008S MX RED with white LED CORSAIR AX850 
CaseMouseMouse PadOther
Antec 1200 Microsoft X8 Steelseries QcK Pro Creative XFi 
CPUGraphicsRAMHard Drive
Core i7 @ 2.6  GT650 16GB of 1600 MHz DDR3L SDRAM 256GB SSD 
OSMonitorKeyboard
Mac OSX Lion Retina Display US layout 
  hide details  
Reply
Andr3w's RiG
(16 items)
 
   
CPUMotherboardGraphicsRAM
Intel Core i7 920 @ 4.0 (HT off) ASUS P6TD Deluxe EVGA GTX 580 SC 6GB Corsair XMS3 1600 
Hard DriveCoolingCoolingCooling
2x RAID0 OCZ VERTEX2 SSD 60GB EK FC580GTX EK Supreme HF Laing D5 
OSMonitorKeyboardPower
Windows 7 64 bit / Fedora 16 / Mint 13 DELL S2209W Ducky 9008S MX RED with white LED CORSAIR AX850 
CaseMouseMouse PadOther
Antec 1200 Microsoft X8 Steelseries QcK Pro Creative XFi 
CPUGraphicsRAMHard Drive
Core i7 @ 2.6  GT650 16GB of 1600 MHz DDR3L SDRAM 256GB SSD 
OSMonitorKeyboard
Mac OSX Lion Retina Display US layout 
  hide details  
Reply
post #3 of 5
Thread Starter 
Quote:
Originally Posted by andrewmchugh View Post

As long as sockfile is fine then I can't see a problem because your file writer is fine.
ie this part of your program is fine,
FILE *sockfile = fopen("theFile.txt", "r");
FILE *fp = fopen("theCopy.txt", "w");
int ch;

while ((ch = fgetc(sockfile)) != EOF) {
printf("%c", ch);
fputc(ch, fp);
}

fclose(fp);
fclose(sockfile);
return 0;
Edit,..
Its what I originally thought.
change FILE *fp = fopen("/Users/leekaiwei/Desktop/results.txt", "w");
to FILE *fp = fopen("C:/Users/leekaiwei/Desktop/results.txt", "w"); im guessing that you are in windows... and it will output as expected. I think you would be best not using static paths.

I'm on a Mac actually. The thing is, the printf statement works, I also tried outputting a fixed text into the file e.g. 'hello' and it worked. Just not this request...
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
post #4 of 5
I wrote this, on Windows:
Code:
#define close closesocket /* map */
#define BUFFER 0x1000

int main(int argc, char *argv[]) {

        WSADATA wsaData;
        if ( WSAStartup(MAKEWORD(2,2), &wsaData) != 0 )
                return 1;

        struct addrinfo hints, *res, *res0;
        int error;

        SOCKET conn_s;

        /* init */
        const char* host = "www.google.com";
        memset( &hints, 0, sizeof(hints) );
        hints.ai_family = PF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        /* fetch address hints */
        error = getaddrinfo( host, "http", &hints, &res0 );
        if ( error )
        {
                fprintf( stderr, "%s\n", gai_strerror(error) );
                return 1;
        }

        for ( res = res0; res; res = res->ai_next )
        {
                conn_s = socket(res->ai_family, res->ai_socktype, res->ai_protocol );
                if ( conn_s < 0 )
                {
                        fprintf( stderr, "%s\n", strerror(error) );
                        return 1;
                }

                if ( connect( conn_s, res->ai_addr, res->ai_addrlen ) < 0 )
                {
                        fprintf( stderr, "%s\n", strerror(error) );
                        close( conn_s );
                        return 1;
                }

                break;
        }

        /* set up request */
        char* request = new char[1024];
        const char* format = "GET / HTTP/1.0\r\nHost: %s\r\n\r\n";
        sprintf_s( request, 1024, format, host );

        /* send request */ 
        send( conn_s, request, strlen( request ), 0 );

        /* open file */
        FILE* fh = fopen( "C:\\result.txt", "w" );

        if ( !fh )
                return 1;

        while ( 1 )
        {
                int bytes;
                char buffer[ BUFFER + 10 ];
                bytes = recvfrom( conn_s, buffer, BUFFER, 0, 0, 0 );

                if ( bytes == -1 )
                {
                        /* failed to get the bytes */
                        fprintf( stderr, "%s\n", strerror(error) );
                        return 1;
                }

                buffer[ bytes ] = '\0';
                fprintf( fh, "%s", buffer );

                if ( !bytes )
                        break;
        }

        /* clean up */
        fclose( fh );
        free( request );
        freeaddrinfo( res0 );
        close( conn_s );

        WSACleanup();
        return 0;
}

All you should need to do is change SOCKET to a file descriptor (Windows uses a file handle instead) and remove the WSA init and clean up. And remove the #define for closesocket.
My System
(30 items)
 
"Zeus"
(13 items)
 
 
CPUMotherboardGraphicsRAM
Intel Core i5 2500K (4.5ghz @ 1.320v) Gigabyte Z68X-UD3R-B3 MSI R7970 Lightning Corsair 16GB (4x4GB) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Crucial M4 128GB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 7 Ultimate 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2212HM Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Microsoft IntelliMouse Optical  XTRAC Ripper XXL 
AudioAudioAudioAudio
Westone W3 IEMs RE-272 IEMs Shure SE-215 IEMs Schiit Bifrost DAC 
AudioAudio
Schiit Asgard 2 amp HiVi Swan M50W 2.1 
CPUMotherboardGraphicsRAM
Intel Core i7 950 GA-X58-UD3R Radeon HD 5450  24GB Corsair @ 1333mhz 
Hard DriveOSPowerCase
4x WD Cavair Red 1TB in RAID 0 Windows Server 2008 R2 x64 Corsair HX-520 LianLi LanCool 
  hide details  
Reply
My System
(30 items)
 
"Zeus"
(13 items)
 
 
CPUMotherboardGraphicsRAM
Intel Core i5 2500K (4.5ghz @ 1.320v) Gigabyte Z68X-UD3R-B3 MSI R7970 Lightning Corsair 16GB (4x4GB) 
Hard DriveHard DriveHard DriveHard Drive
Plextor PX-256M5S 256GB Crucial M4 128GB Hitachi HDS721010CLA332 Hitachi HDS723020BLA642 
Hard DriveHard DriveHard DriveOptical Drive
Hitachi HDS723020BLA642 Hitachi HUA722010CLA330 WDC WD10EARS-00Z5B1 TSSTcorp CDDVDW SH-S223B 
CoolingCoolingOSMonitor
Phanteks PH-TC14PE with TY-140's Lamptron FCv5 (x2) Windows 7 Ultimate 64-bit Dell U2412M 
MonitorMonitorMonitorKeyboard
Dell U2412M Dell U2212HM Dell U2212HM Ducky DK9087 G2 Pro 
PowerCaseMouseMouse Pad
Corsair AX-750 Corsair Obsidian 650D Microsoft IntelliMouse Optical  XTRAC Ripper XXL 
AudioAudioAudioAudio
Westone W3 IEMs RE-272 IEMs Shure SE-215 IEMs Schiit Bifrost DAC 
AudioAudio
Schiit Asgard 2 amp HiVi Swan M50W 2.1 
CPUMotherboardGraphicsRAM
Intel Core i7 950 GA-X58-UD3R Radeon HD 5450  24GB Corsair @ 1333mhz 
Hard DriveOSPowerCase
4x WD Cavair Red 1TB in RAID 0 Windows Server 2008 R2 x64 Corsair HX-520 LianLi LanCool 
  hide details  
Reply
post #5 of 5
Thread Starter 
Here is my updated code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>


int main(int argc, char *argv[]) {

    int conn_s = socket(AF_INET, SOCK_STREAM, 0);
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;
    
    struct addrinfo *addr = (struct addrinfo *) calloc(1, sizeof(struct addrinfo));
    
    getaddrinfo("google.com", "80", &hints, &addr);
    
    connect(conn_s, addr->ai_addr, sizeof(struct sockaddr_in));
    
    char *http_request = "GET / HTTP/1.1\n\n";
    
    send(conn_s, http_request, strlen(http_request), 0);
    FILE *sockfile = (FILE *) fdopen(conn_s, "r");
    FILE *fp = fopen("/Users/leekaiwei/Desktop/results.txt", "w+");
    int ch;
    while ((ch = fgetc(sockfile)) != EOF) {
            fprintf(fp, "%c", ch);
        }

    close(conn_s);
    fclose(fp);
    fclose(sockfile);
    free(addr);
    return 0;
}

The problem is that the while becomes and infinite loop due to EOF not working for this socket business. I tested the EOF with a local file and it worked perfectly.
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
My Computer
(22 items)
 
   
CPUMotherboardGraphicsGraphics
Intel Core 2 Quad Core Q6600 Asus P5NE-SLI Asus GTX 460 TOP 1GB Asus GTX 460 TOP 768MB 
RAMRAMHard DriveHard Drive
4GB (2x2GB) Patriot Viper DDR2 SDRAM 8500 4GB (2X2GB) Kingston ValueRam DDR2 SDRAM 6400 Samsung 840 250GB SSD Seagate Barracuda 1TB 
Hard DriveOptical DriveCoolingCooling
Western Digital 2TB NEC DVD+/-RW ATA 2x Red L.E.D. 120mm Case Fan Asus V Series 
OSMonitorMonitorKeyboard
Windows 8 Professional N 64-bit Iiyama PLX436S 17" Samsung SyncMaster 21" Microsoft Sidewinder X4 
PowerCaseMouseMouse Pad
Cooler Master GX 450W EZCOOL Mesh Design Mid Tower Case Razer Deathadder Razer Goliathus 
AudioOther
M-Audio Audiophile 2496 ASMedia PCI-E SATA Controller 
CPUGraphicsGraphicsRAM
Intel I7 2720QM 2.2GHz AMD ATI Radeon HD 6750M Intel HD Graphics 3000 2x2GB DDR3 
Hard DriveHard DriveOptical DriveCooling
SATA 750GB 5400RPM Samsung 830 128GB SSD 8x slot-loading SuperDrive (DVD±R DL/DVD±RW/CD-RW) 2 Fans 
OSOSMonitorKeyboard
Apple Mac OSX Lion 64-bit Microsoft Windows 8 Professional N 64-bit 1680x1050 Hi-Res Antiglare Full-size backlit keyboard 
PowerCaseMouse
77.5-watt-hour lithium-polymer battery Precision Aluminium Unibody Multi-Touch Trackpad 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Application Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Application Programming › Copying contents of file in C