/*
SD card basic file example
This example shows how to create and destroy an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SD.h>
File myFile;
String FileName = "read.txt"; //此处更改文件名称
char* fileName = (char*)(FileName.c_str());
String name;
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT);
if (!SD.begin(4)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
if (SD.exists(fileName)) {
name = FileName +" exists.";
Serial.println(name);
}
else {
name = FileName +" doesn't exist.";
Serial.println(name);
}
// open a new file and immediately close it:
name = "Creating " + FileName;
Serial.println(name);
myFile = SD.open(fileName, FILE_WRITE);
myFile.close();
// Check to see if the file exists:
if (SD.exists(fileName)) {
String name = FileName +" create succeed.";
Serial.println(name);
}
else {
String name = FileName +" create failure.";
Serial.println(name);
}
// open the file for read and immediately close it:
name = "Opening " + FileName;
Serial.println(name);
myFile = SD.open(fileName, FILE_READ);
// Check to see if the file opened:
if (myFile) {
String name = FileName +" open succeed.";
Serial.println(name);
}
else {
String name = FileName +" open failure.";
Serial.println(name);
}
myFile.close();
// delete the file:
name = "Removing " + FileName;
Serial.println(name);
SD.remove(fileName);
if (SD.exists(fileName)){
String name = FileName +" exist.";
Serial.println(name);
}
else {
String name = FileName +" doesn't exist.";
Serial.println(name);
}
}
void loop()
{
// nothing happens after setup finishes.
}