讀取文本
#include <stdio.h>c
#include <stdlib.h>
int main(void)
{
FILE* fp = fopen("C:\\Users\\Administrator\\Documents\\GitHub\\smart\\c_hik_ren\\read_me.txt", "r");
if(!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
int c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
if (ferror(fp))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}
圖片轉爲二進制流並寫入txt
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fopen_s(&fp,"C:\\Users\\Administrator\\Pictures\\test.jpg", "rb");
if(fp == NULL) {
perror("File opening failed");
return EXIT_FAILURE;
}
fseek(fp, 0, SEEK_END);
long int size = ftell(fp);
rewind(fp);
printf("get the size is: %ld\n", size);
char* ImgBuffer=(char*)malloc( size* sizeof(char) );
fread(ImgBuffer, size, 1, fp);
fclose(fp);
if ( (fp=fopen("C:\\Users\\Administrator\\Pictures\\a.txt", "wb"))==NULL)
{
perror("txtxFile opening failed");
exit(0);
}
fwrite(ImgBuffer, size, 1, fp);
printf("ok");
fclose(fp);
free(ImgBuffer);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define IMAGE_PATH "../"
#define SAVE_IMG ".jpeg"
#define SAVE_TXT ".txt"
char* genRandomString(int length)
{
int flag, i;
char* string;
srand((unsigned) time(NULL ));
if ((string = (char*) malloc(length)) == NULL )
{
printf("Malloc failed!flag:14\n");
return NULL ;
}
for (i = 0; i < length - 1; i++)
{
flag = rand() % 3;
switch (flag)
{
case 0:
string[i] = 'A' + rand() % 26;
break;
case 1:
string[i] = 'a' + rand() % 26;
break;
case 2:
string[i] = '0' + rand() % 10;
break;
default:
string[i] = 'x';
break;
}
}
string[length - 1] = '\0';
return string;
}
void saveImg(char * pre, char* ImgBuffer, int size, char *save_format){
char buff[1024]=IMAGE_PATH;
char *s=genRandomString(10);
strcat(buff, pre);
strcat(buff,s);
strcat(buff,save_format);
FILE *fp;
if ( (fp=fopen(buff, "wb+"))==NULL)
{
perror("image fopen fall");
exit(0);
}
fwrite(ImgBuffer, size, 1, fp);
fclose(fp);
}
int main(void)
{
FILE *fp;
fopen_s(&fp,"C:\\Users\\Administrator\\Pictures\\qtblog1.png", "rb");
if(fp == NULL) {
perror("File opening failed");
return EXIT_FAILURE;
}
fseek(fp, 0, SEEK_END);
long int size = ftell(fp);
rewind(fp);
printf("get the size is: %ld\n", size);
char* ImgBuffer=(char*)malloc( size* sizeof(char) );
fread(ImgBuffer, size, 1, fp);
fclose(fp);
saveImg("ren", ImgBuffer, size, SAVE_IMG);
free(ImgBuffer);
}
int main() {
FILE *fp;
fopen_s(&fp,"C:\\Users\\Administrator\\Pictures\\test.jpg", "rb");
if(fp == NULL) {
perror("File opening failed");
return EXIT_FAILURE;
}
char pBuffer[8];
FILE * wp = fopen("C:\\Users\\Administrator\\Pictures\\2.jpg", "wb");
while (!feof(fp)){
fread(pBuffer, 1, 3, fp);
fwrite(pBuffer, 1, 3, wp);
}
fclose(fp);
fclose(wp);
printf("Hello, World!\n");
return 0;
}