当前位置:文档之家› C语言文件操作大全

C语言文件操作大全

C语言文件操作大全
C语言文件操作大全

1.创建文件夹

//using System.IO;

Directory.CreateDirectory(%%1);

2.创建文件

//using System.IO;

File.Create(%%1);

3.删除文件

//using System.IO;

File.Delete(%%1);

4.删除文件夹

//using System.IO;

Directory.Delete(%%1);

5.删除一个目录下所有的文件夹

//using System.IO;

foreach (string dirStr in Directory.GetDirectories(%%1)) {

DirectoryInfo dir = new DirectoryInfo(dirStr);

ArrayList folders=new ArrayList();

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

for (int i = 0; i < folders.Count; i++)

{

FileInfo f = folders[i] as FileInfo;

if (f == null)

{

DirectoryInfo d = folders[i] as DirectoryInfo;

d.Delete();

}

}

}

6.清空文件夹

//using System.IO;

Directory.Delete(%%1,true);

Directory.CreateDirectory(%%1);

7.读取文件

//using System.IO;

StreamReader s = File.OpenText(%%1);

string %%2 = null;

while ((%%2 = s.ReadLine()) != null){

}

s.Close();

8.写入文件

//using System.IO;

FileInfo f = new FileInfo(%%1);

StreamWriter w = f.CreateText();

w.WriteLine(%%2);

w.Close();

9.写入随机文件

//using System.IO;

byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray); using(FileStream FileStream = new FileStream(%%1, FileMode.Create)){

// Write the data to the file, byte by byte.

for(int i = 0; i < dataArray.Length; i++){

FileStream.WriteByte(dataArray[i]);

}

// Set the stream position to the beginning of the file.

FileStream.Seek(0, SeekOrigin.Begin);

// Read and verify the data.

for(int i = 0; i < FileStream.Length; i++){

if(dataArray[i] != FileStream.ReadByte()){

//写入数据错误

return;

}

}

//"数据流"+https://www.doczj.com/doc/198290702.html,+"已验证"

}

10.读取文件属性

//using System.IO;

FileInfo f = new FileInfo(%%1);//f.CreationTime,f.FullName

if((f.Attributes & FileAttributes.ReadOnly) != 0){

%%2

}

else{

%%3

}

11.写入属性

//using System.IO;

FileInfo f = new FileInfo(%%1);

f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;

//设置可写

f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;

12.枚举一个文件夹中的所有文件夹

//using System.IO;

foreach (string %%2 in Directory.GetDirectories(%%1)){

%%3

}

/*

DirectoryInfo dir = new DirectoryInfo(%%1);

FileInfo[] files = dir.GetFiles("*.*");

foreach(FileInfo %%2 in files){

%%3

}

*/

13.复制文件夹

/*

using System.IO;

using System.Collections;

*/

string path = (%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%2.Length - 1) ? %%2 : %%2+"\\";

string parent = Path.GetDirectoryName(%%1);

Directory.CreateDirectory(path + Path.GetFileName(%%1));

DirectoryInfo dir = new DirectoryInfo((%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%1.Length - 1) ? %%1 : %%1 + "\\");

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(dir.GetFileSystemInfos()); while (Folders.Count>0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

Directory.CreateDirectory(d.FullName.Replace((https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == parent.Length - 1) ? parent : parent + "\\", path));

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

f.CopyTo(f.FullName.Replace(parent, path));

}

}

14.复制目录下所有的文件夹到另一个文件夹下

/*

using System.IO;

using System.Collections;

*/

DirectoryInfo d = new DirectoryInfo(%%1);

foreach (DirectoryInfo dirs in d.GetDirectories())

{

Queue al = new Queue(dirs.GetFileSystemInfos());

while (al.Count > 0)

{

FileSystemInfo temp = al.Dequeue();

FileInfo file = temp as FileInfo;

if (file == null)

{

DirectoryInfo directory = temp as DirectoryInfo;

Directory.CreateDirectory(path + https://www.doczj.com/doc/198290702.html,);

foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())

al.Enqueue(fsi);

}

else

File.Copy(file.FullName, path + https://www.doczj.com/doc/198290702.html,);

}

}

15.移动文件夹

/*

using System.IO;

using System.Collections;

*/

string filename = Path.GetFileName(%%1);

string path=(%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%2.Length - 1) ? %%2 : %%2 + "\\";

if (Path.GetPathRoot(%%1) == Path.GetPathRoot(%%2))

Directory.Move(%%1, path + filename);

else

{

string parent = Path.GetDirectoryName(%%1);

Directory.CreateDirectory(path + Path.GetFileName(%%1));

DirectoryInfo dir = new DirectoryInfo((%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%1.Length - 1) ? %%1 : %%1 + "\\");

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(dir.GetFileSystemInfos());

while (Folders.Count > 0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == parent.Length - 1) ? parent : parent + "\\", path));

dpath.Create();

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

f.MoveTo(f.FullName.Replace(parent, path));

}

}

Directory.Delete(%%1, true);

}

16.移动目录下所有的文件夹到另一个目录下

/*

using System.IO;

using System.Collections;

*/

string filename = Path.GetFileName(%%1);

if (Path.GetPathRoot(%%1) == Path.GetPathRoot(%%2))

foreach (string dir in Directory.GetDirectories(%%1))

Directory.Move(dir, https://www.doczj.com/doc/198290702.html,bine(%%2,filename));

else

{

foreach (string dir2 in Directory.GetDirectories(%%1))

{

string parent = Path.GetDirectoryName(dir2);

Directory.CreateDirectory(https://www.doczj.com/doc/198290702.html,bine(%%2,

Path.GetFileName(dir2)));

string dir = (https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == dir2.Length - 1) ? dir2 : dir2 + "\\";

DirectoryInfo dirdir = new DirectoryInfo(dir);

FileSystemInfo[] fileArr = dirdir.GetFileSystemInfos();

Queue Folders = new Queue(dirdir.GetFileSystemInfos());

while (Folders.Count > 0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == parent.Length - 1) ? parent : parent + "\\", %%2));

dpath.Create();

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

f.MoveTo(f.FullName.Replace(parent, %%2));

}

}

dirdir.Delete(true);

}

}

17.以一个文件夹的框架在另一个目录创建文件夹和空文件

/*

using System.IO;

using System.Collections;

*/

bool b=false;

string path = (%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%2.Length - 1) ? %%2 : %%2 + "\\";

string parent = Path.GetDirectoryName(%%1);

Directory.CreateDirectory(path + Path.GetFileName(%%1));

DirectoryInfo dir = new DirectoryInfo((%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%1.Length - 1) ? %%1 :

%%1 + "\\");

FileSystemInfo[] fileArr = dir.GetFileSystemInfos();

Queue Folders = new Queue(dir.GetFileSystemInfos()); while (Folders.Count > 0)

{

FileSystemInfo tmp = Folders.Dequeue();

FileInfo f = tmp as FileInfo;

if (f == null)

{

DirectoryInfo d = tmp as DirectoryInfo;

Directory.CreateDirectory(d.FullName.Replace((https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == parent.Length - 1) ? parent : parent + "\\", path));

foreach (FileSystemInfo fi in d.GetFileSystemInfos())

{

Folders.Enqueue(fi);

}

}

else

{

if(b) File.Create(f.FullName.Replace(parent, path));

}

}

18.复制文件

//using System.IO;

File.Copy(%%1,%%2);

19.复制一个文件夹下所有的文件到另一个目录

//using System.IO;

foreach (string fileStr in Directory.GetFiles(%%1))

File.Copy((%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + "\\"+Path.GetFileName(fileStr),(%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\\"+Path.GetFileName(fileStr));

20.提取扩展名

//using System.IO;

string %%2=Path.GetExtension(%%1);

21.提取文件名

//using System.IO;

string %%2=Path.GetFileName(%%1);

22.提取文件路径

//using System.IO;

string %%2=Path.GetDirectoryName(%%1);

23.替换扩展名

//using System.IO;

File.ChangeExtension(%%1,%%2);

24.追加路径

//using System.IO;

string %%3=https://www.doczj.com/doc/198290702.html,bine(%%1,%%2);

25.移动文件

//using System.IO;

File.Move(%%1,%%2+"\\"+file.getname(%%1));

26.移动一个文件夹下所有文件到另一个目录

foreach (string fileStr in Directory.GetFiles(%%1))

File.Move((%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%1.Length - 1) ? %%1 +Path.GetFileName(fileStr): %%1 + "\\"+Path.GetFileName(fileStr),(%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\\"+Path.GetFileName(fileStr));

27.指定目录下搜索文件

/*

using System.Text;

using System.IO;

*/

string fileName=%%1;

string dirName=%%2;

DirectoryInfo dirc=new DirectoryInfo(dirName);

foreach(FileInfo file in dirc.GetFiles()) {

if(https://www.doczj.com/doc/198290702.html,.IndexOf(fileName)>-1)

return file.FullName;

}

foreach(DirectoryInfo dir in dirc.GetDirectories()) {

return GetFile(fileName,dir.FullName);

}

return "找不到指定的文件";

}

28.打开对话框

OpenFileDialog openFileDialog=new OpenFileDialog();

openFileDialog.InitialDirectory=\"c:\\\\\";//注意这里写路径时要用c:\\\\而不是c:\\ openFileDialog.Filter=\"文本文件|*.*|C#文件|*.cs|所有文件|*.*\";

openFileDialog.RestoreDirectory=true;

openFileDialog.FilterIndex=1;

if (openFileDialog.ShowDialog()==DialogResult.OK) {

fName=openFileDialog.FileName;

File fileOpen=new File(fName);

isFileHaveName=true;

%%1=fileOpen.ReadFile();

%%1.AppendText(\"\");

}

29.文件分割

//using System.IO;

FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);

byte[] btArr = new byte[fsr.Length];

fsr.Read(btArr, 0, btArr.Length);

fsr.Close();

string strFileName=%%1.Substring(%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\")+1);

FileStream fsw = new FileStream(%%2 + strFileName + "1", FileMode.Create, FileAccess.Write); fsw.Write(btArr, 0, btArr.Length/2);

fsw.Close();

fsw = new FileStream(%%2 + strFileName + "2", FileMode.Create, FileAccess.Write);

fsw.Write(btArr, btArr.Length/2, btArr.Length-btArr.Length/2);

fsw.Close();

30.文件合并

//using System.IO;

string strFileName = %%1.Substring(%%https://www.doczj.com/doc/198290702.html,stIndexOf("\\") + 1);

FileStream fsr1 = new FileStream(%%2 + strFileName + "1", FileMode.Open, FileAccess.Read); FileStream fsr2 = new FileStream(%%2 + strFileName + "2", FileMode.Open, FileAccess.Read); byte[] btArr = new byte[fsr1.Length+fsr2.Length];

fsr1.Read(btArr, 0, Convert.ToInt32(fsr1.Length));

fsr2.Read(btArr, Convert.ToInt32(fsr1.Length), Convert.ToInt32(fsr2.Length));

fsr1.Close();fsr2.Close();

FileStream fsw = new FileStream(%%2 + strFileName, FileMode.Create, FileAccess.Write); fsw.Write(btArr, 0, btArr.Length);

fsw.Close();

31.文件简单加密

//using System.IO;

//读文件

FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);

byte[] btArr = new byte[fsr.Length];

fsr.Read(btArr, 0, btArr.Length);

fsr.Close();

for (int i = 0; i < btArr.Length; i++){ //加密

int ibt = btArr[i];

ibt += 100;

ibt %= 256;

btArr[i] = Convert.ToByte(ibt);

}

//写文件

string strFileName = Path.GetExtension(%%1);

FileStream fsw = new FileStream(%%2+"/" + "enc_" + strFileName, FileMode.Create, FileAccess.Write);

fsw.Write(btArr, 0, btArr.Length);

fsw.Close();

32.文件简单解密

//using System.IO;

FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);

byte[] btArr = new byte[fsr.Length];

fsr.Read(btArr, 0, btArr.Length);

fsr.Close();

for (int i = 0; i < btArr.Length; i++){//解密

int ibt = btArr[i];

ibt -= 100;

ibt += 256;

ibt %= 256;

btArr[i] = Convert.ToByte(ibt);

}

//写文件

string strFileName = Path.GetExtension(%%1);

FileStream fsw = new FileStream(%%2 +"/" + strFileName, FileMode.Create, FileAccess.Write); fsw.Write(btArr, 0, btArr.Length);

fsw.Close();

33.读取ini文件属性

//using System.Runtime.InteropServices;

//[DllImport("kernel32")]//返回取得字符串缓冲区的长度

//private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retV al,int size,string filePath);

string Section=%%1;

string Key=%%2;

string NoText=%%3;

string iniFilePath="Setup.ini";

string %%4=String.Empty;

if(File.Exists(iniFilePath)){

StringBuilder temp = new StringBuilder(1024);

GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);

%%4=temp.ToString();

}

34.合并一个目录下所有的文件

//using System.IO;

FileStream fsw = new FileStream(%%2, FileMode.Create, FileAccess.Write);

foreach (string fileStr in Directory.GetFiles(%%1))

{

FileStream fsr1 = new FileStream(fileStr, FileMode.Open, FileAccess.Read);

byte[] btArr = new byte[fsr1.Length];

fsr1.Read(btArr, 0, Convert.ToInt32(fsr1.Length));

fsr1.Close();

fsw.Write(btArr, 0, btArr.Length);

}

fsw.Close();

35.写入ini文件属性

//using System.Runtime.InteropServices;

//[DllImport("kernel32")]//返回0表示失败,非0为成功

//private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);

string Section=%%1;

string Key=%%2;

string V alue=%%3;

string iniFilePath="Setup.ini";

bool %%4=false;

if(File.Exists(iniFilePath))

{

long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);

if(OpStation == 0)

{

%%4=false;

}

else

{

%%4=true;

}

}

36.获得当前路径

string %%1=Environment.CurrentDirectory;

37.读取XML数据库

//using System.Xml;

XmlDocument doc=new XmlDocument();

doc.Load(%%1);

string %%9;

XmlElement xe=doc.GetElementById(%%7);

XmlNodeList elemList=xe.ChildNodes;

foreach(XmlNode elem in elemList)

{

if(elem.NodeType==%%8)

{

%%9=elem.V alue;

break;

}

}

38.写入XML数据库

//using System.Xml;

XmlDocument doc=new XmlDocument();

doc.Load(%%1);

XmlNode root=doc.DocumentElement;

XmlElement book=doc.CreateElement(%%3);

XmlElement book=doc.CreateElement(%%5);

XmlElement port=doc.CreateElement(%%6);

book.SetAttribute(%%4,root.ChildNodes.Count.ToString());

author.InnerText=%%8;

book.appendChild(author);

book.appendChild(port);

root.appendChild(book);

doc.Save(%%1);

39.ZIP压缩文件

/*

using System.IO;

using https://www.doczj.com/doc/198290702.html,pression;

*/

FileStream infile;

try

{

// Open the file as a FileStream object.

infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);

byte[] buffer = new byte[infile.Length];

// Read the file to ensure it is readable.

int count = infile.Read(buffer, 0, buffer.Length);

if (count != buffer.Length)

{

infile.Close();

//Test Failed: Unable to read data from file

return;

}

infile.Close();

MemoryStream ms = new MemoryStream();

// Use the newly created memory stream for the compressed data.

DeflateStream compressedzipStream = new DeflateStream(ms, https://www.doczj.com/doc/198290702.html,press, true);

//Compression

compressedzipStream.Write(buffer, 0, buffer.Length);

// Close the stream.

compressedzipStream.Close();

//Original size: {0}, Compressed size: {1}", buffer.Length, ms.Length);

FileInfo f = new FileInfo(%%2);

StreamWriter w = f.CreateText();

w.Write(buffer,0,ms.Length);

w.Close();

} // end try

catch (InvalidDataException)

{

//Error: The file being read contains invalid data.

} catch (FileNotFoundException)

{

//Error:The file specified was not found.

} catch (ArgumentException)

{

//Error: path is a zero-length string, contains only white space, or contains one or more invalid characters

} catch (PathTooLongException)

{

//Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

} catch (DirectoryNotFoundException)

{

//Error: The specified path is invalid, such as being on an unmapped drive.

} catch (IOException)

{

//Error: An I/O error occurred while opening the file.

} catch (UnauthorizedAccessException)

{

//Error: path specified a file that is read-only, the path is a directory, or caller does not have

the required

permissions.

} catch (IndexOutOfRangeException)

{

//Error: You must provide parameters for MyGZIP.

}

40.ZIP解压缩

/*

using System.IO;

using https://www.doczj.com/doc/198290702.html,pression;

*/

FileStream infile;

try

{

// Open the file as a FileStream object.

infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);

byte[] buffer = new byte[infile.Length];

// Read the file to ensure it is readable.

int count = infile.Read(buffer, 0, buffer.Length);

if (count != buffer.Length)

{

infile.Close();

//Test Failed: Unable to read data from file

return;

}

infile.Close();

MemoryStream ms = new MemoryStream();

// ms.Position = 0;

DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);

//Decompression

byte[] decompressedBuffer = new byte[buffer.Length *2];

zipStream.Close();

FileInfo f = new FileInfo(%%2);

StreamWriter w = f.CreateText();

w.Write(decompressedBuffer);

w.Close();

} // end try

catch (InvalidDataException)

{

//Error: The file being read contains invalid data.

}

catch (FileNotFoundException)

//Error:The file specified was not found.

}

catch (ArgumentException)

{

//Error: path is a zero-length string, contains only white space, or contains one or more invalid characters

}

catch (PathTooLongException)

{

//Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

platforms, paths must be less than 248 characters, and file names must be less than 260 characters. }

catch (DirectoryNotFoundException)

{

//Error: The specified path is invalid, such as being on an unmapped drive.

}

catch (IOException)

{

//Error: An I/O error occurred while opening the file.

}

catch (UnauthorizedAccessException)

{

//Error: path specified a file that is read-only, the path is a directory, or caller does not have the required

permissions.

}

catch (IndexOutOfRangeException)

{

//Error: You must provide parameters for MyGZIP.

}

41.获得应用程序完整路径

string %%1=Application.ExecutablePath;

42.ZIP压缩文件夹

/*

using System.IO;

using https://www.doczj.com/doc/198290702.html,pression;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;

private void CreateCompressFile(Stream source, string destinationName)

{

using (Stream destination = new FileStream(destinationName, FileMode.Create, FileAccess.Write))

{

using (GZipStream output = new GZipStream(destination, https://www.doczj.com/doc/198290702.html,press))

{

byte[] bytes = new byte[4096];

int n;

while ((n = source.Read(bytes, 0, bytes.Length)) != 0)

{

output.Write(bytes, 0, n);

}

}

}

}

ArrayList list = new ArrayList();

foreach (string f in Directory.GetFiles(%%1))

{

byte[] destBuffer = File.ReadAllBytes(f);

SerializeFileInfo sfi = new SerializeFileInfo(f, destBuffer);

list.Add(sfi);

}

IFormatter formatter = new BinaryFormatter();

using (Stream s = new MemoryStream())

{

formatter.Serialize(s, list);

s.Position = 0;

CreateCompressFile(s, %%2);

}

[Serializable]

class SerializeFileInfo

{

public SerializeFileInfo(string name, byte[] buffer)

{

fileName = name;

fileBuffer = buffer;

}

string fileName;

public string FileName

{

get

{

return fileName;

}

}

byte[] fileBuffer;

public byte[] FileBuffer

{

get

{

return fileBuffer;

}

}

}

43.递归删除目录下的文件

//using System.IO;

DirectoryInfo DInfo=new DirectoryInfo(%%1);

FileSystemInfo[] FSInfo=DInfo.GetFileSystemInfos();

for(int i=0;i

{

FileInfo FInfo=new FileInfo(%%1+FSInfo[i].ToString());

FInfo.Delete();

}

44.验证DTD

/*

using System.Xml;

using System.Xml.Schema;

*/

XmlReaderSettings settings = new XmlReaderSettings();

settings.ProhibitDtd = false;

settings.V alidationType = V alidationType.DTD;

settings.V alidationEventHandler += new V alidationEventHandler(V alidationCallBack); // Create the XmlReader object.

XmlReader reader = XmlReader.Create("my book.xml", settings);

// Parse the file.

while (reader.Read());

// Display any validation errors.

private static void V alidationCallBack(object sender, V alidationEventArgs e)

{

Console.WriteLine("V alidation Error: {0}", e.Message);

}

45.Schema 验证

/*

using System.Xml;

using System.Xml.Schema;

*/

Boolean m_success;

XmlV alidatingReader reader = null;

XmlSchemaCollection myschema = new XmlSchemaCollection();

V alidationEventHandler eventHandler = new V alidationEventHandler(ShowCompileErrors);

try

{

//Create the XML fragment to be parsed.

String xmlFrag = "" +

"Herman" +

"Melville" +

"";

//Create the XmlParserContext.

XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

//Implement the reader.

reader = new XmlV alidatingReader(xmlFrag, XmlNodeType.Element, context);

//Add the schema.

myschema.Add("urn:bookstore-schema", "c:\\Books.xsd");

//Set the schema type and add the schema to the reader.

reader.V alidationType = V alidationType.Schema;

reader.Schemas.Add(myschema);

while (reader.Read())

{

}

Console.WriteLine("Completed validating xmlfragment");

}

catch (XmlException XmlExp)

{

Console.WriteLine(XmlExp.Message);

}

catch(XmlSchemaException XmlSchExp)

{

Console.WriteLine(XmlSchExp.Message);

}

catch(Exception GenExp)

{

Console.WriteLine(GenExp.Message);

}

finally

{

Console.Read();

}

public static void ShowCompileErrors(object sender, V alidationEventArgs args)

{

Console.WriteLine("V alidation Error: {0}", args.Message);

}

46.Grep

/*

using System.Collections;

using System.Text.RegularExpressions;

using System.IO;

using System.Security;

using CommandLine.Utility;

*/

//Traditionally grep stands for "Global Regular Expression Print".

//Global means that an entire file is searched.

//Regular Expression means that a regular expression string is used to establish a search pattern.

//Print means that the command will display its findings.

//Simply put, grep searches an entire file for the pattern you want and displays its findings.

//

//The use syntax is different from the traditional Unix syntax, I prefer a syntax similar to

//csc, the C# compiler.

//

// grep [/h|/H] - Usage Help

//

// grep [/c] [/i] [/l] [/n] [/r] /E:reg_exp /F:files

//

// /c - print a count of matching lines for each input file;

// /i - ignore case in pattern;

// /l - print just files (scanning will stop on first match);

// /n - prefix each line of output with line number;

// /r - recursive search in subdirectories;

//

// /E:reg_exp - the Regular Expression used as search pattern. The Regular Expression can be delimited by

// quotes like "..." and '...' if you want to include in it leading or trailing blanks;

//

// /F:files - the list of input files. The files can be separated by commas as in /F:file1,file2,file3

//and wildcards can be used for their specification as in /F:*file?.txt;

//

//Example:

//

// grep /c /n /r /E:" C Sharp " /F:*.cs

//Option Flags

private bool m_bRecursive;

private bool m_bIgnoreCase;

private bool m_bJustFiles;

private bool m_bLineNumbers;

private bool m_bCountLines;

private string m_strRegEx;

private string m_strFiles;

//ArrayList keeping the Files

private ArrayList m_arrFiles = new ArrayList(); //Properties

public bool Recursive

{

get { return m_bRecursive; }

set { m_bRecursive = value; }

}

public bool IgnoreCase

{

get { return m_bIgnoreCase; }

set { m_bIgnoreCase = value; }

}

public bool JustFiles

{

get { return m_bJustFiles; }

set { m_bJustFiles = value; }

}

public bool LineNumbers

{

get { return m_bLineNumbers; }

set { m_bLineNumbers = value; }

}

public bool CountLines

{

get { return m_bCountLines; }

set { m_bCountLines = value; }

}

public string RegEx

{

get { return m_strRegEx; }

c和c语言的文件操作全高效与简洁修订稿

c和c语言的文件操作 全高效与简洁 SANY标准化小组 #QS8QHH-HHGX8Q8-GNHHJ8-HHMHGN#

例一 #include "" int main() {FILE *fp,*f; int a,b,c; fp=fopen("","r"); f=fopen("","w"); fscanf(fp,"%d%d%d",&a,&b,&c); a=5; b=3; fprintf(f,"%d%d",a+b+c,b); fclose(fp); fclose(f); return 0;} 例二、新建一个名为的文件,里面按如图1存储6个数据,然后在同一目录下建立一文件,按图2格式输出这六个数据。 #include "" int main() {FILE *fp,*fpp; int a,b,c,d,e,f; fp=fopen("","r"); fpp=fopen("","w"); fscanf(fp,"%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f); fprintf(fpp,"%d%d%d%d%d%d",a,b,c,d,e,f); fclose(fp); fclose(fpp); return 0;}

c++常用: #include <> ifstream filein(""); // 定义一个文件输入流 ofstream fileout(""); //cout<< --> fileout<< () //文件到末尾,返回非零值 表示输入的数据文件 本地测试的话本来输入的数据就要在这个文件里面测试了 建一个本地的文本,可以用记事本的方式打开 注意:文件输入的话,以后的cin>>都要改成filein>>, cout<<都要改成fileout<< c语言常用: freopen("","r",stdin); //重定向所有标准的输入为文件输入 freopen("","w",stdout);//重定向所有标准的输出为文件输出 fclose(stdout);//输出结束 freopen("","r",stdin); //重定向所有标准的输入为文件输入 freopen("","w",stdout);//重定向所有标准的输出为文件输出 fclose(stdout);//输出结束 第一句的意思就是文件输入,以"读状态",去替换标准的输入 以上如果只是规定用文件输入输出的某一种,那么就只用其中的一种 方法一:最简单的 main() { freopen("","r",stdin);//从中读取数据 freopen("","w",stdout);//输出到文件 } 方法二:速度比第一种快 main() { FILE *in; FILE *out; in=fopen("","r"); //指针指向输入文件

C语言读写文件操作

C语言读写文件操作 #include #include #include FILE *stream;//, *stream2; FILE *stream2; void main( void ) { int numclosed; char *list; list="这个程序由czw编写"; //试图打开文件data.txt,如果该文件不存在,则自动创建 if( (stream= fopen( "data.txt", "r" )) == NULL ) { printf( "试图打开'data.txt'\n" ); printf( "'data.txt'不存在\n" ); printf( "'data.txt'被创建\n" ); } else printf( "'data.txt'被打开\n" ); //以写入方式打开 if( (stream2 = fopen( "data.txt", "w+" )) == NULL ) printf( "'data.txt'不存在\n" ); else { printf( "'data.txt'成功被打开\n" ); fwrite(list,strlen(list),30,stream2); printf("写入数据成功\n"); } //如果文件data.txt存在,就会打开成功,则stream!=NULL,这时就关闭stream if (stream!=NULL) if( fclose( stream) ) printf( "文件流 stream 被关闭\n" ); //关闭所有打开的文件流,返回关闭的文件流个数 numclosed = _fcloseall( );

C语言程序中关于文件的操作

文件操作函数C语言(FILE fputc fgetc fputs fgets fscanf fprintf) 在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之。 一、流式文件操作 这种方式的文件操作有一个重要的结构FILE,FILE在stdio.h中定义如下:typedef struct{ int level;/*fill/empty level of buffer*/ unsigned flags;/*File status flags*/ char fd;/*File descriptor*/ unsigned char hold;/*Ungetc char if no buffer*/ int bsize;/*Buffer size*/ unsigned char_FAR*buffer;/*Data transfer buffer*/ unsigned char_FAR*curp;/*Current active pointer*/ unsigned istemp;/*Temporary file indicator*/ short token;/*Used for validity checking*/ }FILE;/*This is the FILE object*/ FILE这个结构包含了文件操作的基本属性,对文件的操作都要通过这个结构的指针来进行,此种文件操作常用的函数见下表函数功能 fopen()打开流 fclose()关闭流 fputc()写一个字符到流中 fgetc()从流中读一个字符 fseek()在流中定位到指定的字符 fputs()写字符串到流 fgets()从流中读一行或指定个字符 fprintf()按格式输出到流 fscanf()从流中按格式读取 feof()到达文件尾时返回真值 ferror()发生错误时返回其值 rewind()复位文件定位器到文件开始处 remove()删除文件 fread()从流中读指定个数的字符 fwrite()向流中写指定个数的字符 tmpfile()生成一个临时文件流 tmpnam()生成一个唯一的文件名 下面就介绍一下这些函数 1.fopen() fopen的原型是:FILE*fopen(const char*filename,const char*mode),fopen实现三个功

C语言 文件操作

C语言中的文件操作 12.1请编写一个程序,把一个文件的内容复制到另一个文件中。 程序如下: #include main() { char ch; FILE *fp1; FILE *fp2; if((fp1=fopen("C:\\Users\\acer\\Documents\\1.txt","r"))==NULL) { printf("The file 1.txt can not open!"); exit(0); } if((fp2=fopen("C:\\Users\\acer\\Documents\\2.txt","w"))==NULL) { printf("The file 2.txt can not open!"); exit(0); } ch=fgetc(fp1); while(!feof(fp1)) { fputc(ch,fp2); ch=fgetc(fp1); } fclose(fp1); fclose(fp2); } 运行结果: 12.3请编写一个程序,比较两个文件,如果相等则返回0;否则返回1。

程序如下:#include main() { FILE *f1,*f2; char a,b,c; int x; printf("input strings for file1\n"); f1=fopen("file1","w"); while((c=getchar())!= EOF) putc(c,f1); fclose(f1); printf("output strings for file1\n"); f1=fopen("file1","r"); while((c=getc(f1))!= EOF) printf("%c",c); fclose(f1); printf("\n\ninput strings for file2\n"); f2=fopen("file2","w"); while((c=getchar())!= EOF) putc(c,f2); fclose(f2); printf("\noutput strings for file2\n"); f1=fopen("file2","r"); while((c=getc(f2))!= EOF) printf("%c",c); fclose(f2); f2=fopen("file2","r"); getch(); }

Linux下C语言的文件读写

Linux下C语言的文件(fputc,fgetc,fwrite,fread对文件读写操 作) //================================== fputc 向文件写入字符 #include #include main() { FILE *fp; char ch; if((fp=fopen("test.txt","w"))==NULL) { printf("不能打开文件\n"); exit(0); } while ((ch=getchar())!='\n') fputc( ch, fp ); fclose(fp); } ------------- 小提示: fp=fopen("test.txt","w") ,把"w"改为"a" 可以创建文件并且追加写入内容 exit(0); 需要包含stdlib.h 头文件,才能使用 //============================================================ fgetc 读取字符 #include #include main( int argc, char *argv[] ) { char ch;

FILE *fp; int i; if((fp=fopen(argv[1],"r"))==NULL) { printf("不能打开文件\n"); exit(0); } while ((ch=fgetc(fp))!=EOF) putchar(ch); fclose(fp); } 文件结尾,通过判断EOF //============================================================== fwrite 的使用 使数组或结构体等类型可以进行一次性读写 #include #include main() { FILE *fp1; int i; struct student{ char name[10]; int age; float score[2]; char addr[15]; }stu; if((fp1=fopen("test.txt","wb"))==NULL) { printf("不能打开文件"); exit(0); } printf("请输入信息,姓名年龄分数1 分数2 地址:\n"); for( i=0;i<2;i++) { scanf("%s %d %f %f %s",https://www.doczj.com/doc/198290702.html,,&stu.age,&stu.score[0],&stu.score[1], stu.addr);

C语言中关于文件操作

C语言中关于文件操作 C语言中的文件 C语言把文件看作一个字节的序列 C语言对文件的存取是以字节为单位的文本文件(ASCII文件) 按数据的ASCII形式存储 二进制文件 按数据在内存中的二进制形式存储 文本文件和二进制文件 缓冲文件系统 文件类型指针 FILE类型 保存被使用的文件的有关信息 所有的文件操作都需要FILE类型的指针 FILE是库文件中定义的结构体的别名注意不要写成struct FILE 举例 FILE *fp;

FILE类型 typedef struct { short level; /*缓冲区满空程度*/ unsigned flags; /*文件状态标志*/ char fd; /*文件描述符*/ unsigned char hold; /*无缓冲则不读取字符*/ short bsize; /*缓冲区大小*/ unsigned char *buffer; /*数据缓冲区*/ unsigned char *curp; /*当前位置指针*/ unsigned istemp; /*临时文件指示器*/ short token; /*用于有效性检查*/ } FILE; 文件的打开 (fopen函数) 函数原型 FILE *fopen(char *filename, char *mode); 参数说明 filename: 要打开的文件路径 mode: 打开模式 返回值 若成功,返回指向被打开文件的指针 若出错,返回空指针NULL(0) 打开模式描述 r 只读,打开已有文件,不能写 w 只写,创建或打开,覆盖已有文件 a 追加,创建或打开,在已有文件末尾追加 r+ 读写,打开已有文件 w+ 读写,创建或打开,覆盖已有文件 a+ 读写,创建或打开,在已有文件末尾追加 t 按文本方式打开 (缺省) b 按二进制方式打开 文件的打开模式 文件的关闭 (fclose函数) 函数原型 int fclose(FILE *fp); 参数说明 fp:要关闭的文件指针 返回值 若成功,返回0 若出错,返回EOF(-1) 不用的文件应关闭,防止数据破坏丢失

C语言文件操作大全

1.创建文件夹 //using System.IO; Directory.CreateDirectory(%%1); 2.创建文件 //using System.IO; File.Create(%%1); 3.删除文件 //using System.IO; File.Delete(%%1); 4.删除文件夹 //using System.IO; Directory.Delete(%%1); 5.删除一个目录下所有的文件夹 //using System.IO; foreach (string dirStr in Directory.GetDirectories(%%1)) { DirectoryInfo dir = new DirectoryInfo(dirStr); ArrayList folders=new ArrayList(); FileSystemInfo[] fileArr = dir.GetFileSystemInfos(); for (int i = 0; i < folders.Count; i++) { FileInfo f = folders[i] as FileInfo; if (f == null) { DirectoryInfo d = folders[i] as DirectoryInfo; d.Delete(); } } } 6.清空文件夹 //using System.IO; Directory.Delete(%%1,true); Directory.CreateDirectory(%%1); 7.读取文件 //using System.IO; StreamReader s = File.OpenText(%%1); string %%2 = null; while ((%%2 = s.ReadLine()) != null){

c语言中目录及文件操作

1. 错误处理与错误号 cat /usr/include/asm-generic/errno-base.h #define EPERM 1 /* Operation not per mitted */ #define ENOENT 2 /* No suc h file or director y */ #define ESRCH 3 /* No suc h proc ess */ #define EINTR 4 /* Interrupted s y stem call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such dev ice or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Ex ec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No c hild process es */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memor y */ #define EACCES 13 /* Per mission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Bl oc k dev ice required */ #define EBUSY 16 /* Dev ice or resource bus y */ #define EEXIST 17 /* File ex ists */ #define EXDEV 18 /* Cross-dev ice link */ #define ENODEV 19 /* N o suc h dev ice */ #define ENOTDIR 20 /* Not a direc tor y */ #define EISDIR 21 /* Is a director y */ #define EINVAL 22 /* Inv alid argument */ #define ENFILE 23 /* File table ov erflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a ty pewriter */ #define ETXTBSY 26 /* Text file bus y */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* N o space l eft on dev ic e */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-onl y file s y s tem */ #define EMLINK 31 /* T oo many link s */ #define EPIPE 32 /* Brok en pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* M ath r esult not repres entabl e */ 1.1 用错误常数显示错误信息 函数strerror()可以把一个错误常数转换成一个错误提示语句。char *strerror(int errnum); #include #include #include int main()

C语言中文件_数据的输入输出_读写

C语言中文件,数据的输入输出,读写. 文件是数据的集合体,对文件的处理过程就是对文件的读写过程,或输入输出过程。 所谓文件是指内存以外的媒体上以某种形式组织的一组相关数据的有序集合。文件分类: 顺序文件,随机文件。 文本文件和二进制文件。 文本文件也称为ASCII文件,在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。 文本文件可以在屏幕上按字符显示,源程序文件就是文本文件,由于是按字符显示,所以能读懂文件内容。 二进制文件是按二进制编码方式来存放的。这里主要讨论文件的打开,关闭,读,写,定位等操作。 文件的存取方法 C程序的输入输出(I/O)有两种方式:一种称为标准I/O或流式I/O,另一种称为低级I/O。流式I/O是依靠标准库函数中的输入输出函数实现的。低级I/O利用操作系统提供的接口函数(称为底层接口或系统调用)实现输入输出,低级I/O 主要提供系统软件使用。 在C语言中用一个FILE类型的指针变量指向一个文件,(FILE类型是系统在stdio.h中定义的描述已打开文件的一种结构类型),这个指针称为文件指针。FILE *指针变量标识符; 如 FILE *fp; 文件的打开与关闭 所谓打开文件,指的是建立文件的各种有关信息,并使文件指针指向该文件,以便对它进行操作。 关闭文件则是断开指针与文件之间的联系,也就禁止再对该文件进行操作。 1、fopen 函数原型:FILE *fopen(const char *filename,const char *mode); Fopen函数用来打开一个文件,前一部分用来说明文件路径及文件名,后一部分mode指出了打开文件的存取方式;返回值是被打开文件的FILE型指针,若打开失败,则返回NULL。打开文件的语法格式如下: 文件指针名=fopen(文件名,使用文件方式); 文件指针名必须被说明为FILE类型的指针变量。 FILE *fp; fp=fopen(“C:\\Windowss\\abc.txt”,”r”); 注意用两个反斜杠\\来表示目录间的间隔符。 存取文件的模式是一个字符串,可以由字母r,w,a,t,b及+组合而成,各字符的含

c语言程序中文件的操作

文件操作函数 C语言 (FILE fputc fgetc fputs fgets fscanf fprintf) 在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之。 一、流式文件操作 这种方式的文件操作有一个重要的结构FILE,FILE在中定义如下: typedef struct { int level; /* fill/empty level of buffer */ unsigned flags; /* File status flags */ char fd; /* File descriptor */ unsigned char hold; /* Ungetc char if no buffer */ int bsize; /* Buffer size */ unsigned char _FAR *buffer; /* Data transfer buffer */ unsigned char _FAR *curp; /* Current active pointer */ unsigned istemp; /* Temporary file indicator */ short token; /* Used for validity checking */ } FILE; /* This is the FILE object */ FILE这个结构包含了文件操作的基本属性,对文件的操作都要通过这个结构的指针来进行,此种文件操作常用的函数见下表函数功能 fopen() 打开流 fclose() 关闭流 fputc() 写一个字符到流中

C语言 文件练习题

C语言文件练习题 1.系统的标准输入文件是指_________. a)键盘 b)显示器 c)软盘 d)硬盘 2.若执行fopen函数时发生错误,则函数的返回值是______. a)地址值 b)0 c)1 d)EOF 3.若要用fopen函数打开一个新的二进制文件,该文件要既能读也能写,则文件方式字符串应是______. a)"ab+" b)"wb+" c)"rb+" d)"ab" 4.fscanf函数的正确调用形式是______. a)fscanf(fp,格式字符串,输出表列) ) 11.下列关于C语言数据文件的叙述中正确的是________ A)文件由ASCII码字符序列组成,C语言只能读写文本文件 B)文件由二进制数据序列组成,C语言只能读写二进制文件 C)文件由记录序列组成,可按数据的存放形式分为二进制文件和文本文件 D)文件由数据流形式组成,可按数据的存放形式分为二进制文件和文本文件 12.函数fseek(pf, OL,SEEK_END)中的SEEK_END代表的起始点是________ A)文件开始B)文件末尾C)文件当前位置D)以上都不对 13.C语言中,能识别处理的文件为_______ A)文本文件和数据块文件B)文本文件和二进制文件 C)流文件和文本文件D)数据文件和二进制文件

14.若调用fputc函数输出字符成功,则其返回值是________ A)EOF B)1 C)0 D)输出的字符 15 已知函数的调用形式:fread(buf,size,count,fp),参数buf的含义是______ A)一个整型变量,代表要读入的数据项总数 B)一个文件指针,指向要读的文件 C)一个指针,指向要读入数据的存放地址 D)一个存储区,存放要读的数据项 16 当顺利执行了文件关闭操作时,fclose函数的返回值是_________ A)-1 B)TRUE C)0 D)1 17.如果需要打开一个已经存在的非空文件“Demo”进行修改下面正确的选项是______ 盘 d) 为pname指定的相应文件开辟一个缓冲区,调用操作系统提供的打开或 建立新文件功能; 22.利用fwrite (buffer, sizeof(Student),3, fp)函数描述不正确的_________. a) 将3个学生的数据块按二进制形式写入文件; b) 将由buffer指定的数据缓冲区内的3* sizeof(Student)个字节的数据写入指定文件; c) 返回实际输出数据块的个数, 若返回0值表示输出结束或发生了错误; d) 若由fp指定的文件不存在,则返回0值; 23.利用fread (buffer,size,count,fp)函数可实现的操作_________. a) 从fp指向的文件中,将count个字节的数据读到由buffer指出的数据区

C语言程序设计第一章作业

一、单选题(每小题10分,共100分,得分70 分) 1、1.关于C程序的构成描述,_________是不正确的。 A、一个源程序至少且仅包含一个main函数,也可包含一个main函数和若干个其他函数。 B、函数由函数首部和函数体两部分组成,二者缺一不可。 C、函数首部通常是函数的第1行,包括:函数属性、函数类型、函数名、函数参数等,不管有无函数参数,都必须用一对圆括号括起来。 D、函数体通常在函数首部下面,用一对花括号将声明部分和执行部分括起来,但不能为空。 你的回答:D (√) 参考答案:D 2、2.C程序中,不管是数据声明还是语句,都必须有一个结束符,它是C语句的必要组成部分,该符号是_________。 A、逗号“,” B、句号“。” C、分号“;” D、单撇号“’” 你的回答:C (√) 参考答案:C 3、3.下列关于C程序的运行流程描述,______是正确的。 A、编辑目标程序、编译目标程序、连接源程序、运行可执行程序。 B、编译源程序、编辑源程序、连接目标程序、运行可执行程序。 C、编辑源程序、编译源程序、连接目标程序、运行可执行程序。 D、编辑目标程序、编译源程序、连接目标程序、运行可执行程序。 你的回答:C (√) 参考答案:C 4、5.描述或表示算法有多种方法,______不是常用的表示方法。 A、自然语句 B、流程图或N-S图 C、伪代码 D、效果图 你的回答:D (√) 参考答案:D

5、7.C语言是一种结构化的程序设计语言,任何程序都可以将模块通过3种基本的控制结构进行组合来实现,这三种基本的控制结构是指______。 A、分支结构、循环结构、函数结构 B、顺序结构、选择结构、函数结构 C、顺序结构、分支结构、循环结构 D、以上描述都不正确 你的回答:D (×) 参考答案:C 6、下列关于算法特性的描述,______是不正确的。 A、有穷性:指一个算法应该包含有限的操作步骤,而不能是无限的。 B、确定性:指算法的每一个步骤都应当是确定的,不应该是含糊的、模棱两可的。 C、有效性:指算法中的每一个步骤都应当能有效地执行,并得到确定的结果。 D、输入/输出性:指算法中可以有输入/输出操作,也可以没有输入/输出操作。 你的回答:D (√) 参考答案:D 7、关于运行一个C程序的描述,______是正确的。 A、程序总是从main()函数处开始运行,当main()函数执行结束时,程序也就执行结束。 B、程序总是从main()函数处开始运行,当调用其它函数时,也可在其它函数中执行结束。 C、当程序中无main()函数时,可以设置一个主控函数来代替main()函数,从而达到运行程序的目的。 D、以上描述都不正确。 你的回答:B (×) 参考答案:A 8、下列关于C程序中复合语句的描述,______是正确的。 A、用一对圆括号“( )”将若干语句顺序组合起来就形成一个复合语句。 B、用一对大括号“{ }”将若干语句顺序组合起来就形成一个复合语句。 C、用一对大括号“[ ]”将若干语句顺序组合起来就形成一个复合语句。 D、以上描述都不正确。 你的回答:B (√) 参考答案:B 9、一个C源程序文件的扩展名是______。

C语言文件操作命令

C语言文件操作函数大全 clearerr(清除文件流的错误旗标) 相关函数 feof 表头文件 #include 定义函数 void clearerr(FILE * stream); 函数说明 clearerr()清除参数stream指定的文件流所使用的错误旗标。 返回值 fclose(关闭文件) 相关函数 close,fflush,fopen,setbuf 表头文件 #include 定义函数 int fclose(FILE * stream); 函数说明 fclose()用来关闭先前fopen()打开的文件。此动作会让缓冲区内的数据写入文件中,并释放系统所提供的文件资源。 返回值若关文件动作成功则返回0,有错误发生时则返回EOF并把错误代码存到errno。 错误代码 EBADF表示参数stream非已打开的文件。 范例请参考fopen()。 fdopen(将文件描述词转为文件指针) 相关函数 fopen,open,fclose 表头文件 #include 定义函数 FILE * fdopen(int fildes,const char * mode); 函数说明 fdopen()会将参数fildes 的文件描述词,转换为对应的文件指针后返回。参数mode 字符串则代表着文件指针的流形态,此形态必须和原先文件描述词读写模式相同。关于mode 字符串格式请参考fopen()。 返回值转换成功时返回指向该流的文件指针。失败则返回NULL,并把错误代码存在errno中。 范例 #include main() { FILE * fp =fdopen(0,”w+”); fprintf(fp,”%s\n”,”hello!”); fclose(fp); } 执行 hello! feof(检查文件流是否读到了文件尾) 相关函数 fopen,fgetc,fgets,fread 表头文件 #include 定义函数 int feof(FILE * stream); 函数说明 feof()用来侦测是否读取到了文件尾,尾数stream为fopen()所返

C语言文件操作

文件 教学目标:了解文件的概念;熟练掌握缓冲文件系统和非缓冲文件系统的概念及其区别;熟练掌握文件类型指针的概念;熟练掌握打开文件和关闭文件的方法;熟练掌握利用标准I/O提供的四种读写文件的方法对文件进行顺序读写和随机读写;了解文件操作的出错检测方法。 教学重点:缓冲文件系统与非缓冲文件;文件类型指针;文件的打开与关闭;利用标准I/O提供的四种读写文件的方法对文件进行顺序读写和随机读写。 教学难点:缓冲文件系统与非缓冲文件;利用标准I/O提供的四种读写文件的方法对文件进行顺序读写操作和随机读写操作。 §11.1 文件概述 11.1.1 文件的概念 所谓文件是指记录在外部存储介质上的数据集合。例如,用EDLN编辑好的一个源程序就是一个文件,把它存储到磁盘上就是一个磁盘文件。从计算机上输出一个源文件到打印机,这也是一个文件。广义上说,所有输入输出设备都是文件。例如,键盘、显示器、打印机都是文件。计算机以这些设备为对象进行输入输出,对这些设备的处理方法统一按文件处理。 计算机中的文件可以从不同角度进行分类: (1)按文件介质:磁带文件、磁盘文件和卡片文件等。 (2)按文件内容:源程序文件、目标文件、可执行文件和数据文件等。 (3)按文件中数据的组织形式:二进制文件和文本文件。 文本文件是指文件的内容是由一个一个的字符组成,每一个字符一般用该字符对应的ASCII码表示。例如,一个实数136.56占6个字符。二进制文件是以数据在内存中的存储形式原样输出到磁盘上去。例如,实数136.56在内存中以浮点形式存储,占4个字符,而不是6个字节。若以二进制形式输出此数,就将该4个字节按原来在内存中的存储形式送到磁盘上去。不管一个实数有多大,都占4个字节。一般来说,文本文件用于文档资料的保存,方便用户阅读理解;二进制文件节省存储空间而且输入输出的速度比较快。因为在输出时不需要把数据由二进制形式转换为字符代码,在输入时也不需要把字符代码先换成二进制形式然后存入内存。如果存入磁盘中的数据只是暂存的中间结果数据,以后还要调入继续处理,一般用二进制文件以节省时间和空间。如果输出的数据是准备作为文档供给人们阅读的,一般用字符代码文件,它们通过显示器或打印机转换成字符输出,比较直观。 11.1.2 缓冲文件系统和非缓冲文件系统 目前C语言所使用的磁盘文件系统有两大类:一类称为缓冲文件系统,又称为标准文件系统或高层文件系统;另一类称非缓冲文件系统,又称为低层文件系统。 (1)缓冲文件系统的特点 对程序中的每一个文件都在内存中开辟一个“缓冲区”。从磁盘文件输入的数据先送到“输入缓冲区”,然后再从缓冲区依次将数据送给接收变量。在向磁盘文件输出数据时,先将程序数据区中变量或表达式的值送到“输出缓冲区”中,然后

C语言文件操作之绝对路径

C语言中对文件进行操作如何使用绝对路径? 我编了一个小程序试了一下,好像默认的路径是在生成的.exe文件所在目录下。如果使用像D:\\ABC.TXT这样的路径可以在D盘下对ABC.TXT进行操作,但如果使用D:\\SSS\ABC.TXT就不正确了,创建的文件是SSSABC.TXT,不支持多级的路径,它把路径和文件名弄混了。 到底怎么办 D:\\SSS\\ABC.TXT //你少了个\,在C字符串中,出现\的地方,你一律打两个\\就行了。 请问啊,C语言里,fopen、fread与fwrite的参数中,要求文件名,用写盘符吗? 写绝对路径吗?#include #include int main() { FILE *pfile = fopen("d:\\Jimmy.txt","wb");//Jimmy.txt写在D盘根目录下绝对路径//以2进制写入方式打开 //FILE *pfile = fopen("\\Jimmy.txt","wb");//Jimmy.txt写在当前目录下相对路径//以2进制写入方式打开 char sz[6] = "Billy"; fwrite("Jimmy",6,1,pfile);//将字串"Jimmy"写入文件pfile fclose(pfile); pfile = fopen("d:\\Jimmy.txt","rb");//以2进制读取方式打开绝对路径,D盘根目录 //pfile = fopen("\\Jimmy.txt","rb");//以2进制读取方式打开相对路径,当前路径 printf(sz);//显示原字串 printf("\n"); fread((char*)sz,6,1,pfile);//由开头读入6字节信息 printf(sz);//显示读取的信息 printf("\n"); fclose(pfile); system("pause"); return 0; }

C语言常用语句总结

C语言常用语句总结 一:常用函数 1、putchar函数: putchar函数(字符输出函数):向终端输出一个字符。 一般形式为: putchar(c)// 输出字符变量c的值。== printf(“%c”,c) 2、getchar函数 getchar函数(字符输入函数):从终端输入一个字符。 getchar函数没有参数,一般形式为: c=getchar() //将输入的字符赋值给c 3、printf函数 printf函数(格式输入函数):向终端输出若干个任意类型的数据。 printf的一般格式为: printf(“格式控制”,对应变量名)// 例如:printf(”%d,%c\n”,i,c) 4、scanf函数 scanf(格式输入函数):从终端输入若干个任意类型的数据。 一般形式为: scanf(“格式控制”,&变量名) 二:基本语句(除if语句外,switch和三种循环语句都需要{大括号}的支持) (1)条件语句if和switch 1、if语句: ********************* if(表达式) 语句1; 语句2;// if下的各独立语句用分号分隔。 ********************* if(表达式) 语句1; else 语句2; ********************* if(表达式1)

else if(表达式2) // 每一个if与他最近的一个else对应。 语句2; .... else if(表达式n) 语句n; else 语句n+1; ********************* If语句的嵌套 if(表达式) if(表达式)语句1 else语句2 else if(表达式)语句3 else语句4 2、switch语句 switch (表达式) { case 常量表达式1: 语句1 case常量表达式2: 语句2 // 每一个case表达式后都需要加上break跳出,否则case常量表达式n: 将依次执行下去。 语句n default :// 大括号划分switch内语句 语句n+1 } (2)三种循环语句 1、while语句 while语句用来实现“当型”循环结构。 一般形式如下: while(表达式) // 当表达式非0值时(逻辑表达式),执行while语句中的内嵌套语句,{ 先判断后执行。 语句1; // 分号间隔每一个独立语句。 语句2;// 大括号划分出while内语句。 } 2、do… while 语句 do… while 语句先执行循环体,然后判断循环条件是否成立。

c语言文件操作的语句

文件操作 //1.定义文件类型指针 FILE *fp; //2. 以只读方式打开文件 fp = fopen(“data.in”, “r”); //3. 判断文件打开是否失败 if (fp==NULL){ printf(“Error 1\n”); return 1; } // 4. 判断整型数据输入是否非法 // ①文件为空或数据格式不符致使输入不成功,即没读到数据 //②输入数据不合题意(假设题目要求31 &&n < 10) { // ①|| !②printf (“Error 2\n”); fclose(fp); //关闭文件 return 2; } // 5. 判断字符串输入是否非法 // ①文件为空或数据格式不符致使输入不成功,即没读到字符串str //②输入数据不合题意(假设题目要求串长strlen(str)<80)lenth = strlen( (str, 80, fp)

if ( !(0< lenth && lenth <80) ) { // fgets失败返回0 printf (“Error 2\n”); fclose(fp); //关闭文件 return 2; } // 6. 判断字符输入是否非法: // ①文件为空或数据格式不符致使输入不成功,即没读到字符ch //②输入数据不合题意(假设题目要求ch为数字) if ( ch = fgetc(fp) == EOF || !(…0?<=ch && ch<=’9’ ) ) { // ①||!②printf (“Error 2\n”); fclose(fp); //关闭文件 return 2; } //7. 调用fscanf函数从文件输入n个学生信息的结构体型数据 #define SIZE 60 struct student_type{ unsigned long num; char name[10]; int score[3]; }stud[SIZE];

C语言文件操作函数freopen

freopen 目录 函数简介 程序例 函数简介 函数名: freopen 功能: 替换一个流,或者说重新分配文件指针,实现重定向。如果stream流已经打开,则先关闭该流。如果该流已经定向,则freopen将会清除该定向。此函数一般用于将一个指定的文件打开一个预定义的流:标准输入、标准输出或者标准出错。 用法: FILE *freopen(const char *filename,const char *type, FILE *stream); 头文件:stdio.h 返回值:如果成功则返回该指向该stream的指针,否则为NULL。 程序例 举例1: #include int main() { /* redirect standard output to a file */ if (freopen("D:OUTPUT.txt", "w", stdout)==NULL) fprintf(stderr, "error redirecting stdout\n"); /* this output will go to a file */ printf("This will go into a file."); /* close the standard output stream */ fclose(stdout); return 0; } 举例2: 如果上面的例子您没看懂这个函数的用法的话,请看这个例子。这个例子实现了从stdout到一个文本文件的重定向。即,把输出到屏幕的文本输出到一个文本文件中。 #include int main() { int i; if (freopen("D:OUTPUT.txt", "w", stdout)==NULL) fprintf(stderr, "error redirecting\stdout\n"); for(i=0;i<10;i++) printf("%3d",i); printf("\n"); fclose(stdout);

相关主题
文本预览
相关文档 最新文档