菜鸟学习笔记--10.11

1、fpeintf:
fprintf是C/C++中的一个格式化写—库函数,位于头文件<stdio.h>中,其作用是格式化输出到一个流/文件中;
函数原型:
int fprintf (FILE* stream, const char*format, [argument])
FILE*stream:文件指针
const char* format:输出格式
[argument]:附加参数列表
fprintf( )会根据参数format 字符串来转换并格式化数据, 然后将结果输出到参数stream 指定的文件中, 直到出现字符串结束('\0')为止。
fprintf()的返回值是输出的字符数,发生错误时返回一个 负值.
eg1:
#include <stdio.h>
int main(void) {
    FILE *FSPOINTER;
    char STRBUFF[16] = "Hello World.";
    FSPOINTER = fopen("HELLO.TXT", "w+")
    fprintf(FSPOINTER, "%s", STRBUFF)
    return 0;
}
输出至文件HELLO.TXT:
Hello World
eg2:
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
FILE* stream;
int main(void)
{
    int i = 10;
    double fp = 1.5;
    char s[] = "this is a string";
    char c = '\n';
    stream = fopen("fprintf.out", "w");
    fprintf(stream, "%s%c", s, c);
    fprintf(stream, "%d\n", i);
    fprintf(stream, "%f\n", fp);
    fclose(stream);
    system("typefprintf.out");
    return 0;
}
输出至文件fprintf.out:
this is a string
10
1.500000
eg3:
fprintf(stderr,"hefowfjofjoi    \n" );
stderr: Unix标准输出(设备)文件,对应终端的屏幕;

2、malloc
malloc函数是一种分配长度为num_bytes字节的内存块的函数,可以向系统申请分配指定size个字节的内存空间
函数原型:
extern void *malloc(unsigned int num_bytes);
该函数返回为 void型指针,因此必要时要进行类型转换。
如果分配成功则返回指向被分配内存的 指针(此存储区中的初始值不确定),否则返回空指针 NULL。当内存不再使用时,应使用free()函数将内存块释放。
malloc 只管分配内存, 并不对所得的内存进行初始化,所以得到的一片新内存中,其 值将是随机的。
eg1:
type *p;
if(NULL == (p = (type*)malloc(sizeof(type))))
/*请使用if来判断,这是有必要的*/
{
    perror("error...");
    exit(1);
}
.../*其它代码*/
free(p);
p = NULL;/*请加上这句*/

3、memcpy
函数原型:
void *memcpy(void *dest, const void *src, size_t n);
memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中;C语言:#include<string.h>

strcpy和memcpy主要有以下3方面的区别。
1、复制的内容不同。 strcpy只能复制 字符串,而memcpy可以复制任意内容,例如 字符数组、整型、 结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy

eg1: 将s中第13个字符开始的4个连续字符复制到d中。(从0开始)
#include<string.h>
int main(
{
    char* s="GoldenGlobalView";
    char d[20];
    memcpy(d,s+12,4);//从第13个字符(V)开始复制,连续复制4个字符(View)
    d[4]='\0';//memcpy(d,s+12*sizeof(char),4*sizeof(char));也可
    printf("%s",d);
   getchar();
   return 0;
}

 
     

















猜你喜欢

转载自blog.csdn.net/sdhotn/article/details/78209806